Combining loop “for” with statement “if”

awk

I've created a script for awk. I'm combining loop "for" with "if" statement. It's searching each line for word "ABC" which can occure in different place in the line. It looks like below:

{for (i=1;i<=NF;i++) if ($i=="ABC") print $(i-2)}

The problem appears when there is no "ABC" in the line and I would like to print an information about it. With script as below it gaves me an information for each word from the line which is different than "ABC" and I would like ONLY ONE information for line (not for each word).

{for (i=1;i<=NF;i++) if ($i=="ABC") print $(i-2)

else if ($i=="ABC") print "no ABC in the line"}

Regards,
lucas

Best Answer

You have told your script to explicitly check through each field (word) of the line. What you want to do is simply check if the line anywhere contains the string ABC:

awk '{
      if(/ABC/){
        printf "line %s contains ABC
      }
       else{
       printf "line %s does not contain ABC\n",NR
      }
     }' file.txt

If you run this on a file with the following contents:

 this line has no string of interest
 this line contains ABC somewhere

you get:

line 1 does not contain ABC
line 2 contains ABC

You did not explain why you were printing $(i-2) but if that is what you really need, you can do:

awk '{k=0; for (i=1;i<=NF;i++){
            if ($i=="ABC"){print $(i-2); k++}
           } 
           if(k==0){print "No ABC in line",NR}
     }' file.txt

The trick is the variable k. It is set to 0 at the beginning of each line. When you go through the fields, if one of them matches ABC, k is set to 1. Therefore, once all the fields have been processed, if k is still 0, the line contained no ABC and a message is printed. Running this script on the example file I gave above prints:

No ABC in line 1
line
Related Question