Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've created a statement which is searching for specific informations in each line (in my case "AAA","BBB" or "CCC"), if there is no such information N/A is printed

{ k=0; for (i=1;i<=NF;i++) if ($i=="AAA") {print $i; k++}

else if ($i=="BBB") {print $i; k++}

else if ($i=="CCC") {print $i; k++}

if(k==0) print "N/A"}

The problem appears when there are two or more "AAA" in the same line. It prints me all found AAA and I would like to stop searching after first finded.

Additionally I would like to stop checking other statements (for BBB or CCC) when AAA contition is true.

For examle, let's say I have an input like that:

first imput line has AAA

second line has AAA and AAA

third line has BBB and

fourth line has CCC

fifth line has AAA and CCC

last line

in the output I want:

AAA #(from first line)

AAA #(from second line, but only first found, I don't want two AAA to be printed)



AAA #(it found AAA and stop checking condition for CCC)

N/A #(no AAA or BBB or CCC in this line)

Regards, lucas

share|improve this question
awk '{
    if (/\<AAA\>/ && /\<BBB\>/ && /\<CCC\>/)
       print "N/A"

\< and \> are word boundary expressions.

share|improve this answer
ok, but it prints me all line, and I want only to print that specific information (AAA or BBB or CCC). Moreover it seems that it works only when all 3 statments are true for the line. If one of them is false it prints me N/A. – lucas Dec 13 '13 at 22:35
Edit your question to show some sample input and your desired output – glenn jackman Dec 14 '13 at 19:11
I've found an answer, the solution is magic instruction break which stops a loop after first finding. updated code with instruction break: { k=0; for (i=1;i<=NF;i++) if ($i=="AAA") {print $i; k++; break} else if ($i=="BBB") {print $i; k++; break} else if ($i=="CCC") {print $i; k++; break} if(k==0) print "N/A"}` and all works perfect :) – lucas Dec 17 '13 at 16:36
awk '
/\<AAA\>/ {print "AAA"; naflag = 1;}
/\<BBB\>/ {print "BBB"; naflag = 1;}
/\<CCC\>/ {if(cflag == 0) {print "CCC"; naflag = 1; cflag = 1;}}
{if(naflag == 0) print "N/A"; naflag = 0;}
share|improve this answer
That doesn't seem right. Firstly, your curly braces are not balanced properly. Second even if you balance them, it seems your solution is tuned for this answer. Second CCC is not printed, but it is the first CCC that prevents second CCC not to be printed, not AAA. – infiniteRefactor Mar 22 at 20:15
your explanation of what you want isn't very clear. Can you explain in more detail? – Bing Bang Mar 24 at 19:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.