Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

unix - How do I delete a matching line and the previous one?

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**
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}'

And as a single line

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...