Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...