3

I'd like to delete two lines in a file, containing pattern aaa bbb ccc.

I have used the following expression, which deletes the line containing pattern aaa bbb ccc and the line before.

$ sed -n '/aaa bbb ccc/{s/.*//;x;d;};x;p;${x;p;}' file.txt | sed '/^$/d'

This works for one file. It doesn't work for multiple files

$ for i in *.txt; do sed -n '/aaa bbb ccc/{s/.*//;x;d;};x;p;${x;p;}' "$i" | sed '/^$/d'; done

example file:

xxx
yyy
aaa bbb ccc
eee
fff
aaa bbb ccc
ggg
hhh

result file:

xxx
eee
ggg
hhh
xralf
  • 15,415

1 Answers1

7

Looks like you're using gnu sed - in that case you can do something like

sed -s 'N;/PATTERN/!P;D' ./*.txt

With other seds you'd have to loop over the list of files

for file in ./*.txt
do
sed '$!N;/PATTERN/!P;D' "$file"
done

This will always keep two lines in the pattern space and print the first one if the pattern space doesn't match so with an input like

some line
PATTERN
PATTERN
more
lines
another line
PATTERN

it will print

more
lines
don_crissti
  • 82,805
  • One detail. The above command writes only to standard output. When I extend the command as follows ... "$file" > "$file", it will delete the content of the file, instead of replacing it with modified content. – xralf May 24 '17 at 12:51
  • @xralf - it's quite surprising that someone who has been here for over six years doesn't know what some command "$file" > "$file" does (that is, truncating the file)... I mean, really, it has been asked and answered a million times... – don_crissti May 24 '17 at 14:44
  • In many subjects I haven't started learning from the beginning, but because I needed to have something done. I usually tell to myself, I will learn it from the beginning someday. :-) Thanks anyway, when I have serenity time, I like helping others as well. – xralf May 25 '17 at 07:01
  • 1
    @xralf - no problem, that's how I've learned too lol... I wasn't criticizing you, it was just hard to believe that you had never tried (even accidentally) to cat file > file or seen similar posts here (they pop up every other week or so...) – don_crissti May 25 '17 at 11:05