awk - output comming strange: for operator ~ and == .

Hi awk experts,

I am getting a strange output , may be it is normal but I am unable to comprehend,

When Using == operator it is showing correct:

# ls -l | awk '{for (i=0;i<=NF;i++) if ( $i =="info" )print $1,$6,$7,$8,$9}'
drwx------ Jan 17 10:44 info

But When using ~ (equal ) operator: two line output comes, when data has only one line only:

# ls -l | awk '{for (i=0;i<=NF;i++) if ( $i ~ "info" )print $1,$6,$7,$8,$9}'
drwx------ Jan 17 10:44 info
drwx------ Jan 17 10:44 info

Can you guys please explain, whats wrong happening here,
Thank you,

start loop at i=1

1 Like

Try:

ls -l | awk '{for (i=1;i<=NF;i++) if ( $i ~ "info" )print $1,$6,$7,$8,$9}'
1 Like

awk != perl - arrays start indexing with 1 (not 0):

for (i=1;i<=NF;i++)

You can probably figure out what happens when you do pattern matching with $0

1 Like

rdrtx1 , Scrutinizer , vgresh99 Thank you , I got it , loop should be started with 1, thanks a lot.