简体   繁体   English

您可以使用sed删除匹配项,之后仅删除某些行吗?

[英]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? 是否可以使用sed搜索特定的代码块并删除匹配项,并且仅删除匹配项后的特定行?

For example, if I have a block like this, and want to delete special marker 1 and only the second line after it: 例如,如果我有一个像这样的块,并且想删除特殊标记1和仅其后的第二行:

special marker 1
text 1
text 2
text 3

Can I use sed to search for instances of the block and come out with: 我可以使用sed搜索该块的实例并得出:

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打印以跳过两行:

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您可以执行以下操作:

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. 尝试遵循awk解决方案一次。

Solution 1st: 解决方案1:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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