Mike Q
Mike Q

Reputation: 7337

remove lines after second pattern sed

I'm looking to trim a file and I need to remove everything after the second match (and everything before the first match).

For example Say I have this text:

xxx xxx
yyy yyy
New USB device found
xxx xxx
yyy yyy
zzz zzz
New USB device found
xxx xxx
yyy yyy

If I use the following sed command :

sed -i '1,/New USB device found/d' <FILE>  

this removes everything before the first match. which is great:

New USB device found
xxx xxx
yyy yyy
zzz zzz
New USB device found
xxx xxx
yyy yyy

But I'm only 1/2 way there, now I want to remove everything after the 2nd match to get this result:

New USB device found
xxx xxx
yyy yyy
zzz zzz

Hence just the data for the first device.

Upvotes: 2

Views: 2692

Answers (4)

Fredrik Pihl
Fredrik Pihl

Reputation: 45670

using sed:

sed -n '/New/{:a;p;n; /New/!ba}' input

Upvotes: 1

Cole Tierney
Cole Tierney

Reputation: 10324

Here's a sed solution:

sed -i '1,/New USB device found/d; /New USB device found/,$d' <FILE>

Upvotes: 1

Kent
Kent

Reputation: 195229

This awk one-liner should give what you want:

awk '/New USB device found/{p++}p==1' file

test with your data:

kent$  awk '/New USB device found/{p++}p==1' file
    New USB device found
    xxx xxx
    yyy yyy
    zzz zzz

Upvotes: 8

Chris Seymour
Chris Seymour

Reputation: 85883

If you have GNU awk then:

$ awk 'NR==2{print RS,$0}' RS='New USB device found' file
New USB device found 
xxx xxx
yyy yyy
zzz zzz

Just compare the record number you want to print against NR. This makes printing the 112th record as easy as print the 4th record just by changing NR==2 to NR==112 or NR==4.

Upvotes: 2

Related Questions