LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   Sed: insert a newline. Why does not it work? (http://www.linuxquestions.org/questions/linux-software-2/sed-insert-a-newline-why-does-not-it-work-158806/)

J_Szucs 03-17-2004 01:46 AM

Sed: insert a newline. Why does not it work?
 
I want to replace "," by newline in each line, and I tried this:
echo "first,second,third" | sed 's/,/\n/g'

It poduced this:
firstnsecondnthird
(no newlines there :-()

So I tried this:
echo "first,second,third" | sed 's/,/'"$(printf '\n')"'/g'

Which produced this:
firstsecondthird
(still no newlines there :-(((((()

There are millions of sed examples like this on the internet, so why dos not it work for me?
Is there a workaround?

druuna 03-17-2004 02:52 AM

It does work if you do it like this:

echo "one,two,three" | sed 's/,/\
/g'


After the backslash you just hit return, you will get the PS2 prompt (probably >) and continue with the /g' part.

From within a script I do like this sollution, when using this from the command line I do like this one better:

echo "first,second,third" | awk 'BEGIN { FS=","; OFS="\n" } { print $1, $2, $3 }'

Hope this helps.

J_Szucs 03-17-2004 04:48 AM

Well, your example with sed really works from the command line, but, actually I want to use it from a script.
(Only it was easier to test possible commands from the command line)

The awk command would be OK, but that presumes that there are always 3 fields ($1, $2,$3), while in my case there can be any number of fields on the line.

In the meantime I found that tr is the best to it:
echo "first,second,third" | tr ',' '\n'

Result:
first
second
third

It is just what I want.

bysin 04-11-2004 08:39 PM

Try this instead:


echo "one,two,three" | sed "s/,/\\`echo -e '\n\r'`/g"


All times are GMT -5. The time now is 01:53 AM.