# printing only first finded match

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)

BBB

CCC

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

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

Regards, lucas

-

``````awk '{
if (/\<AAA\>/ && /\<BBB\>/ && /\<CCC\>/)
print
else
print "N/A"
}'
``````

`\<` and `\>` are word boundary expressions.

-
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;}
'
``````
-
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