Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

awk '{
    if (/\<AAA\>/ && /\<BBB\>/ && /\<CCC\>/)
       print
    else
       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

Your Answer

 
discard

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.