Palace Chan
Palace Chan

Reputation: 9183

in place replace with sed but only to keep a subset of the lines

I want to run an inplace command for sed to keep only certain lines in a file. This is different from the usual usage where a sed -i with a substitution command is used to in-place substitute a files lines. For example, say I have this file:

> cat file.txt
fox
rabbit
fox
fox
wolf

and I want to only keep the lines matching fox. My idea was:

sed -inr '/fox/p' file.txt

but this does not work as expected. What am I missing?

Upvotes: 1

Views: 322

Answers (2)

Ed Morton
Ed Morton

Reputation: 203254

You're missing the fact that "-i" takes an optional argument so -inr is not the same as -i -n -r, it's the same as -i"nr". Try:

sed -i -nr '/fox/p' file

Upvotes: 2

Kent
Kent

Reputation: 195039

try this line:

sed -i '/fox/!{s/.//g}' file

this will empty those unmatched lines by not delete them. So fox lines are staying in their places.

if you just want to delete those unmatched lines:

sed -i '/fox/!d' file

Upvotes: 1

Related Questions