Chris
Chris

Reputation: 1219

Keep only first line with matching pattern

Does anyone know how I can search a file for a string, then delete all lines except for the one with the first occurrence of the pattern?

E.g., from

sheep
cow
pig
pig
goat

to

pig

where pig is the first line with that pattern.

I know how to delete lines that don't contain a pattern:

sed -i -e '/PATTERN/!d' file

No idea how to only keep the first occurrence, though.

Upvotes: 0

Views: 716

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52132

You could tell sed to quit after the first match:

sed -i '/pig/!d;q' infile

This works because when d is hit, the rest of the commands is ignored, so q will only be executed after the first match.

Or you could use the -m option of grep (works for both GNU and BSD grep, but isn't required by POSIX):

grep -m1 'pig' infile > infile.tmp && mv infile.tmp infile

Upvotes: 2

Related Questions