Remove line containing certain string and the following line
If you have GNU sed (so non-embedded Linux or Cygwin):
sed '/bar/,+1 d'
If you have bar
on two consecutive lines, this will delete the second line without analyzing it. For example, if you have a 3-line file bar
/bar
/foo
, the foo
line will stay.
If bar
may occur on consecutive lines, you could do:
awk '/bar/{n=2}; n {n--; next}; 1' < infile > outfile
which can be adapted to delete more than 2 lines by changing the 2 above with the number of lines to delete including the matching one.
If not, it's easily done in sed
with @MichaelRollins' solution or:
sed '/bar/,/^/d' < infile > outfile
I am not fluent in sed, but it is easy to do so in awk:
awk '/bar/{getline;next} 1' foo.txt
The awk script reads: for a line containing bar, get the next line (getline), then skip all subsequent processing (next). The 1 pattern at the end prints the remaining lines.
Update
As pointed out in the comment, the above solution did not work with consecutive bar
. Here is a revised solution, which takes it into consideration:
awk '/bar/ {while (/bar/ && getline>0) ; next} 1' foo.txt
We now keep reading to skip all the /bar/ lines.