我如何删除匹配的行和前一行? [英] How do I delete a matching line and the previous one?

查看:292
本文介绍了我如何删除匹配的行和前一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除一条匹配的行和之前的一行。
例如在下面的文件中,我需要删除行1& 2。

I need delete a matching line and one previous to it. e.g In file below I need to remove lines 1 & 2.

我试过了grep -v -B 1页面。1.txt
,不打印matchning行和上下文。

I tried "grep -v -B 1 "page.of." 1.txt and I expected it to not print the matchning lines and the context.

我试过了如何使用sed删除匹配的行,上面的行和下面的行? ,但无法理解sed的用法。

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**


推荐答案

你想做一些非常类似于给出的答案

You want to do something very similar to the answer given

sed -n '
/page . of ./ { #when pattern matches
n #read the next line into the pattern space
x #exchange the pattern and hold space
d #skip the current contents of the pattern space (previous line)
}

x  #for each line, exchange the pattern and hold space
1d #skip the first line
p  #and print the contents of pattern space (previous line)

$ { #on the last line
x #exchange pattern and hold, pattern now contains last line read
p #and print that
}'

并作为单行

sed -n '/page . of ./{n;x;d;};x;1d;p;${x;p;}' 1.txt

这篇关于我如何删除匹配的行和前一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆