replacing comma's with newlines using sed

Hi All,
silly question that I'm sure is easy to answer for a more experienced coder...

I have a file called test.txt containing the following text...

need, to, break, this, line, into, individual, lines

using sed, I'd like to make the file look like this...

need
to
break
this
line
into
individual
lines

here's the code I've tried

#!/bin/ksh
sed "s/,/\n/" test.txt > test.new.txt

but it returns the following in test.new.txt
Addn this, line, after, every, line, with, WORD

so, my questions are...
1.) how can I make sed replace all instances of "," in a given line?
2.) how can I make sed insert newline characters instead of just the character n?

Thanks in advance!

d@DeCobox-Micro ~
$ cat unix 
need, to, break, this, line, into, individual, lines

$ cat unix |sed 's/\,/\n/g'
need
 to
 break
 this
 line
 into
 individual
 lines

d@DeCobox-Micro ~
$ cat unix |tr "," "\n"
need
 to
 break
 this
 line
 into
 individual
 lines

d@DeCobox-Micro ~
$ cat unix |tr "," "\n" |tr -d "^ "
need
to
break
this
line
into
individual
lines
1 Like

See if this works for you:

cat test.txt | sed 's/, /\n/g'

Don't forget to add the space after the coma otherwise you will end up with spaces on the new lines.

Vic.

If \n don't work try:

$ echo 'foo, bar' | sed 's/, /\
/g'
foo
bar

Or awk:

$ echo 'foo, bar' | awk -F', ' '{for(i=1;i<=NF;i++) printf "%s\n", $i}'
1 Like

the basic algorithm/steps to do this, is to split the line on "," and then print them out with newline

for line in open("file"):
    line = line.split(",")
    for items in line:
        print items

Thanks good one