printing only first finded match

1

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

lucas

Posted 2013-12-13T20:28:48.530

Reputation: 47

Answers

0

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

\< and \> are word boundary expressions.

glenn jackman

Posted 2013-12-13T20:28:48.530

Reputation: 18 546

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 – 2013-12-13T22:35:25.827

Edit your question to show some sample input and your desired output – glenn jackman – 2013-12-14T19:11:28.513

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  – 2013-12-17T16:36:15.030

-2

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

Bing Bang

Posted 2013-12-13T20:28:48.530

Reputation: 159

1That 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 – 2016-03-22T20:15:09.643

your explanation of what you want isn't very clear. Can you explain in more detail? – Bing Bang – 2016-03-24T19:52:30.147