user3461823
user3461823

Reputation: 1403

Multiple sed vs sed using pipe

I'm trying to convert file wich could have one or more lines and extract word "three". Sample file is oneliner:

[test@test tmp]$ cat test1
onetwothreefourfive[pi@pidora tmp]$

I could make it in this way:

[test@test tmp]$ sed -e 's/.*two\(.*\)four.*/\1/' test1
three[pi@pidora tmp]$

But I have to make sure that my file is oneliner, so I'm using command from this question: How can I replace a newline (\n) using sed?

[test@test tmp]$ sed -e ':a;N;$!ba;s/\n/ /g' -e 's/.*two\(.*\)four.*/\1/' test1
onetwothreefourfive[pi@pidora tmp]$

It doesn't work.

[test@test tmp]$ sed -e ':a;N;$!ba;s/\n/ /g' test1| sed -e 's/.*two\(.*\)four.*/\1/'
three[test@test tmp]$

I use pipe and it works. Please explain to me why sed works wrong without pipe.

Thanks!

Upvotes: 2

Views: 923

Answers (2)

Cyrus
Cyrus

Reputation: 88583

Replace N by $!N or use a brackets:

sed ':a;$!{N;ba;};s/\n/ /g;s/.*two\(.*\)four.*/\1/' test1

Answer to your next question: I don't know why it works.

Upvotes: 1

Nir Levy
Nir Levy

Reputation: 12953

when you run one sed command with two manipulations, they are both being executed on the original text, so your second manipulations does not 'see' the \n added by the first one.

When you run it with the pipe, the second command is executed on the output from the first one, so the second command 'sees' the \n's

Upvotes: 0

Related Questions