Bash sed delete before and after the found line

I currently have the following code:

sed -i "/# My Comment Text/,+2d" /etc/crontab

This removes 2 lines after this line '# My Comment Text', but I also want it to delete 1 line above this found line. How can I resolve this in my 1 liner sed command?

+4
source share
2 answers

Here are 2 sed commands to do the trick. If your input file looks like

1
2
3
4 # My Comment Text
5
6
7
8

We want to delete lines 3,4,5,6.

$ sed '/# My Comment Text/ {h;N;N;g}' file  | tac | sed '/# My Comment Text/,+1d' | tac
1
2
7
8

The first sed command removes 2 lines after the matched line without deleting the matched line.
Then we will cancel the file and delete the matched line and the line after (which is the previous line in the regular file.
Cancel the input and we are done.

+1
source

. gsed mac GNU sed. linux sed.

$ seq 10 | sed 's/^5/5 # my comment text/' | gsed -e ':b;$!{N;1bb;};/# my comment text/,+2!P;D' 1 2 3 7 8 9 10

0

Source: https://habr.com/ru/post/1694739/


All Articles