Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract only the first instance of a number of lines between two strings in bash?

Tags:

shell

sed

awk

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?

like image 276
Vyom Maitreya Avatar asked Oct 26 '25 07:10

Vyom Maitreya


2 Answers

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.
like image 116
RavinderSingh13 Avatar answered Oct 29 '25 05:10

RavinderSingh13


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.

like image 23
JRFerguson Avatar answered Oct 29 '25 06:10

JRFerguson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!