如何删除匹配的行和前一行?
我需要删除匹配的行及其前面的一行。 例如,在下面的文件中,我需要删除第 1 行和第 3 行。 2.
我尝试了“grep -v -B 1”page.of.”1.txt 我希望它不会打印匹配行和上下文。
我尝试了 如何使用 sed 删除匹配的行,即上面的行和下面的行? 但无法理解 sed 的用法。
---1.txt--
**document 1** -> 1
**page 1 of 2** -> 2
testoing
testing
super crap blah
**document 1**
**page 2 of 2**
I need delete a matching line and one previous to it.
e.g In file below I need to remove lines 1 & 2.
I tried "grep -v -B 1 "page.of." 1.txt
and I expected it to not print the matchning lines and the context.
I tried the How do I delete a matching line, the line above and the one below it, using sed? but could not understand the sed usage.
---1.txt--
**document 1** -> 1
**page 1 of 2** -> 2
testoing
testing
super crap blah
**document 1**
**page 2 of 2**
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您想做的事情与 给出的答案
并作为一行
You want to do something very similar to the answer given
And as a single line
grep -v -B1
不起作用,因为它会跳过这些行,但稍后会包含它们(由于-B1
的原因)。要检查这一点,请尝试以下命令:您会注意到
page 2
行将被跳过,因为该行不会匹配,并且下一个 like 也不会匹配有一个简单的 awk 解决方案:
awk 命令如下所示:
如果当前。该行有“页面...... ",那么它将表明您尚未找到有效的行。如果您没有找到该字符串,则打印上一行(存储在 buf 中)并将缓冲区重置为当前行(因此强制它滞后1)
grep -v -B1
doesnt work because it will skip those lines but will include them later on (due to the-B1
. To check this out, try the command on:You will notice that the
page 2
line will be skipped because that line won't be matched and the next like wont be matched.There's a simple awk solution:
The awk command says the following:
If the current line has that "page ... of ", then it will signal that you haven't found a valid line. If you do not find that string, then you print the previous line (stored in buf) and reset the buffer to the current line (hence forcing it to lag by 1)
对 sed 不太熟悉,但这里有一个 perl 表达式可以解决这个问题:
编辑:
其中“xxxx”是您要匹配的内容。
Not too familiar with sed, but here's a perl expression to do the trick:
edit:
where "xxxx" is what you are trying to match.
谢谢,我试图使用 Foo Bah 给出的 awk 命令
删除匹配行和上一行。我必须多次使用它,因此对于匹配部分我使用一个变量。给定的 awk 命令有效,但是当使用变量时它不起作用(即它不会删除匹配的 & 上一行)。我尝试过:
awk -vvar="page.*of.*" '!/$var/ { if (m) print buf;缓冲区=$0; m=1} /$var/ {m=0}' 1.txt
Thanks, I was trying to use the awk command given by Foo Bah
to delete the matching line and the previous one. I have to use it multiple times, so for the matching part I use a variable. The given awk command works, but when using a variable it does not work (i.e. it does not delete the matching & prev. line). I tried:
awk -vvar="page.*of.*" '!/$var/ { if (m) print buf; buf=$0; m=1} /$var/ {m=0}' 1.txt