用 sed/awk 注释掉 N 行
如何注释掉特定模式及 N 行以后的行?
int var1;
int var2;
int var3;
int var4;
int var5;
我想注释掉 3 行,包括 var2 (而不是根据它们的内容!):
int var1;
// int var2;
// int var3;
// int var4;
int var5;
How can I comment out lines from a certain pattern and N lines onwards?
int var1;
int var2;
int var3;
int var4;
int var5;
I want to comment out 3 lines including var2 (and not according to their content!):
int var1;
// int var2;
// int var3;
// int var4;
int var5;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这需要 GNU
sed
This requires GNU
sed
GNU awk(也许其他 awks 也是如此)有模式范围:
或者写得可读:
编辑:
有效,所以我认为范围是 AWK 规范的一部分。您还可以将增量放入范围模式中以节省一些击键。
它将第一个操作应用于包括与 var2 匹配的行在内的行,然后直到 c == 2。
它将第二个模式应用于每一行。
GNU awk (maybe other awks too) has pattern ranges:
Or written readably:
Edit:
works, so I think ranges are part of the AWK spec. You can also put the increment in the range pattern to save some keystrokes.
It applies the first action to lines including the one that matches var2, and after until c == 2.
It applies the second pattern to every line.
还有这个脚本:
sed -i '2,4 s:^://:' test.txt
test.txt:
输出:
Also this script:
sed -i '2,4 s:^://:' test.txt
test.txt:
output:
以下
awk
脚本可以满足您的要求:输出:
它的工作方式相对简单。计数器变量
c
决定还有多少行需要注释。它从 0 开始,但当您找到特定模式时,它会被设置为 3。然后,它开始倒计时,影响许多行(包括将其设置为 3 的行)。
如果您不太担心可读性,则可以使用较短的:
请注意,只要找到模式,计数就会重置。这似乎是合乎逻辑的处理方式:
如果这不是您想要的,请将
count = 3;
替换为if (count == 0) {count = 3;};
或使用:对于紧凑版本。
The following
awk
script can do what you ask:This outputs:
The way it works is relatively simple. The counter variable
c
decides how many lines are left to comment. It starts as 0 but when you find a specific pattern, it gets set to 3.Then, it starts counting down, affecting that many lines (including the one that set it to 3).
If you're not that worried about readability, you can use the shorter:
Be aware that the count will be reset whenever the pattern is found. This seems to be the logical way of handling:
If that's not what you wanted, replace
count = 3;
withif (count == 0) {count = 3;};
or use:for the compact version.