android_su
android_su

Reputation: 1687

how to search a phrase in every two lines with sed

I wanna search a phrase in a doc.
But maybe the phrase was broken up into two lines.
So what I want to do is:
Search in :
line1 and line2
line2 and line3
line3 and line4
......

I am a beginner, and I wanna practise using sed.
So, how can I do this with sed?
Any ideas?


This does not work.

$ sed 'N;s/line2.line3/line23/' test.txt 
line1
line2
line3
line4
line5

1)sed read first line and second line,then search.
2)sed read third line and fourth line,then search.
......
So if the phrase in the line2 and line3, I will miss it.
Can I read the previous line?


update

Thanks for @Beta 's help.

sed '$!N;s/line2.line3/line23/;P;D;'

It works. But I'm still a little confused.
There're still some questions.

I have read the manual.

n:read the next line of input into the pattern space.
N:append the next line of input into the pattern space.
d:Delete pattern space. Start next cycle.
D:Delete up to the first embedded newline in the pattern space. Start next cycle, but skip reading from the input if there is still data in the pattern space.

sed -n 'N;P' test.txt 

1)sed read first and second line, then print the first line.
2)sed empty its pattern space then read third and fourth line, then print the third line.
Am I right?

sed -n 'N;P;D' test.txt 

1)sed read first and second line, then print the first line.
2)sed do not empty its pattern space then read third, then print the second line.
Am I right?

Why the "next line" has different behaviors in the COMMAND N and n in the 2 commands above?



sed '$!N;s/line2.line3/line23/;P;D;'

ps.I think "$!" is not necessary.

Upvotes: 1

Views: 153

Answers (1)

Beta
Beta

Reputation: 99094

There is more than one way to do it. This is close to what you tried:

sed '$!N;s/line2.line3/line23/;P;D;'

Upvotes: 5

Related Questions