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:
If you run this on a file with the following contents:
you get:
You did not explain why you were printing
$(i-2)
but if that is what you really need, you can do: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 matchesABC
,k
is set to1
. Therefore, once all the fields have been processed, ifk
is still0
, the line contained noABC
and a message is printed. Running this script on the example file I gave above prints: