1

I have some code as shown below. The problem is, is that there are multiple occurrences of the pattern i am using. I was wondering if there is any way to make awk only execute on the first occurence of the pattern so it is not being duplicated in the file ?

Any help is appreciated

Thanks

for Server in $Serverlist; do

                    f2="$(<$1)"
                    awk -vf2="$f2" '/Server N.*1p/{print f2;print;next}1' $Server > tmp
                    mv tmp $Server
    done
  • see e.g. http://stackoverflow.com/questions/20943025/how-can-i-get-sed-to-quit-after-the-first-matching-address-range – Fredrik Pihl Apr 16 '14 at 09:49
  • 2
    You can `exit` after the matched sequence. Also, you can use a flag to indicate if you matched it or not, and then print based on this flag being true or not. – fedorqui Apr 16 '14 at 09:51
  • How would i exit after the matched sequence, wouldnt that require me to exit in the middle of the awk statement ? Also thanks for the link Fredrik Pihl but unless i am mistaken in his case he wants to print lines between two fixed points, not just after the first occurence, also he isnt inputting any more information –  Apr 16 '14 at 10:03

1 Answers1

2
awk -vf2="$f2" '/Server N.*1p/ && !seen {print f2;print;seen=1}1' $Server > tmp

would be the simplest way.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks! That does look very simple.I tried it and it prints the pattern as well though ?(So there are two of the pattern in the output file.) –  Apr 16 '14 at 10:35
  • 2
    For anyone who might want to know adding next back to the end of the awk statement fixed the problem i stated in the above comment `awk -vf2="$f2" '/Server N.*1p/ && !seen {print f2;print;seen=1;next}1' $Server > tmp` –  Apr 16 '14 at 10:45