2

Assume I want to remove the 2nd and 3rd, but not the 4th line in the following file (those which match foo but do not match bar), can I easily do this with e.g. sed?

text
foo some more text
even more foo text
some foo text with bar
  • Has to be with sed? – Braiam Oct 27 '14 at 17:19
  • No, other "quick and dirty" tools are fine as well, it was just that sed looked like the most straightforward at first. Actually Stéphane's answer showed that lots of other tools works just as well. – quazgar Oct 27 '14 at 21:08
4

Several alternatives:

awk '! (/foo/ && !/bar/)'
awk '/bar/ || !/foo/'
sed -e /bar/b -e /foo/d
sed '/foo/{/bar/!d;}'
perl -ne 'print unless /foo/ && !/bar/'

GNU grep with PCRE support:

grep -vP '^(?!.*bar).*foo'

(using PCRE's negative look-ahead operator (?!...)).

Of those, only perl allows in-place editing portably (on systems where any version of perl is installed) with the -i option.

Standard sed doesn't do in-place editing. However the sed of some recent BSDs allow it with the -i '' option and GNU sed with -i (both modelled after perl) as an extension.

Very recent versions of GNU awk also allow it with -i inplace.

| improve this answer | |
  • Creating an alias for yourself? – G-Man Says 'Reinstate Monica' Oct 27 '14 at 15:26
  • @G-Man, see meta.unix.stackexchange.com/q/3230 – Stéphane Chazelas Oct 27 '14 at 15:29
  • I see. Funny how they have the resources to change the UI, but not to make the changes that users ask for. Sigh. – G-Man Says 'Reinstate Monica' Oct 27 '14 at 15:38
  • Accepting this one, because I like the diversity of answers. I will probably use one of the sed answers in practice, because sed allows in-place modifiaction of files, which is what I need (but did not specify in the question). – quazgar Oct 27 '14 at 21:19
5

It seems to work for me this way:

sed '/foo/{/bar/!d;}' my_file
| improve this answer | |
  • If the lines would have different content this would not necessarily delete the second and third line and leave the fourth alone as specified as a requirement in the question. – Anthon Oct 27 '14 at 9:47
  • @Anthon, the requirement is in the question's subject. How can I remove lines matching foo but not matching bar?. And this answer addresses it. – Stéphane Chazelas Oct 27 '14 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.