Reputation: 21
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?
Upvotes: 1
Views: 171
Reputation: 133518
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
Upvotes: 1
Reputation: 20002
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
Upvotes: 3
Reputation: 785156
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
Upvotes: 1