简体   繁体   中英

Can you use sed to delete match and only certain lines after?

Is it possible to use sed to search for a particular block of code and delete the match and only a particular line after it?

For example, if I have a block like this, and want to delete special marker 1 and only the second line after it:

special marker 1
text 1
text 2
text 3

Can I use sed to search for instances of the block and come out with:

text 1
text 3

I am aware of commands like:

sed -i '/START/,/END/ {/special marker 1/{n;n;N;d;}}' filename;

However, this command only leaves me with:

text 1

So it seems to double the next line operation and deletes. Any way to fix this command or do this another way?

Tell sed to print to skip the 2 lines:

sed -ni '/special marker 1/{n;p;n;n};p' filename

When you only want two lines output, the command can be replaced by

sed -ni '/special marker 1/{n;p;n;n;p}' filename

Using awk you can do this:

awk '/special marker 1/{p=NR; next} p && NR==p+2{p=0; next} 1' file
text 1
text 3

try following awk solutions too once.

Solution 1st:

awk '/special marker 1/{;if(getline var){print var;if(getline var1){next};next}} 1'   Input_file

Solution 2nd:

awk '/special marker 1/{getline;if(NF){print};if(NF){;getline};next} 1'  Input_file
sed -i '/START/,/END/ {/special marker 1/{N;N;D};P;d}' filename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM