Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove lines after second pattern sed

Tags:

bash

sed

awk

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.

like image 488
Mike Q Avatar asked Dec 03 '25 04:12

Mike Q


1 Answers

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
like image 78
Kent Avatar answered Dec 04 '25 19:12

Kent