Reputation: 7337
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
Reputation: 10324
Here's a sed solution:
sed -i '1,/New USB device found/d; /New USB device found/,$d' <FILE>
Upvotes: 1
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
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