Numpty
Numpty

Reputation: 1481

Sed/Awk - pull lines between pattern x and y

I've got some large CSV files where I'd like to extract all data between Line X that includes pattern 'x' and Line Y that includes pattern 'y'

For example:

other_data
Header
data
data
data
Footer
other_data

I want to be able to pipe everything between (and including) Header -> Footer to a new file.

Thanks!

Upvotes: 12

Views: 16631

Answers (4)

potong
potong

Reputation: 58478

This might work for you (GNU sed):

 sed '/^Header/,/^Footer/w new_file' file

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85865

Another way with awk:

awk '/Header/,/Footer/' file
Header
data
data
data
Footer

Just redirect the output to save in a newfile:

awk '/Header/,/Footer/' file > newfile

Upvotes: 11

Beta
Beta

Reputation: 99144

It's pretty straightforward in sed:

sed -n '/Header/,/Footer/p'

or

sed '/Header/,/Footer/!d'

Upvotes: 19

FatalError
FatalError

Reputation: 54591

Using awk it's pretty straightforward:

awk '/Header/ { show=1 } show; /Footer/ { show=0 }'

Basically keep state in a variable named show. When we hit the Header we turn it on, Footer we turn it off. While it's on, the show rule executes the default action of printing the record.

Upvotes: 19

Related Questions