My file is:
abc
123
xyz
abc
675
xyz
And I want to extract:
abc
123
xyz
(123 could be anything, the point is I want the first occurrence)
I tried using this:
sed -n '/abc/,/xyz/p' filename
but this is giving me all the instances. How could I get just the first one?
Could you please try following, written and tested with shown samples.
awk '/abc/{found=1} found; /xyz/ && found{exit}' Input_file
OR as per Ed sir's comment for better efficiency try following.
awk '/abc/{found=1} found{print; if (/xyz/) exit}' Input_file
Explanation: Adding detailed explanation for above.
awk ' ##Starting awk program from here.
/abc/{ ##checking condition if a line has abc in it then do following.
found=1 ##Setting found here.
}
found; ##Checking condition if found is SET then print that line.
/xyz/ && found{ ##Checking if xyz found in line and found is SET then do following.
exit ##exit program from here.
}
' Input_file ##Mentioning Input_file name here.
If you don't mind Perl:
perl -ne 'm?abc?..m?xyz? and print' file
will print only the first block that matches. The delimiter for the matches must be the ? character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With