Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace comma with newline in sed on MacOS?

Tags:

unix

macos

sed

I have a file of strings that are comma separated. I'm trying to replace the commas with a new line. I've tried:

sed 's/,/\n/g' file 

but it is not working. What am I missing?

like image 693
WildBill Avatar asked May 25 '12 04:05

WildBill


People also ask

How do you replace a comma with a newline?

Example 1: Replace \n with a comma using -zThe `sed` command will convert the newline into the null character and replace each \n with a comma by using the first search and replace pattern. Here, 'g' is used to globally search for \n. With the second search and replace pattern, the last comma will be replaced with \n.

How do you add a new line in sed?

The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.


2 Answers

Use tr instead:

tr , '\n' < file 
like image 62
Prince John Wesley Avatar answered Oct 17 '22 00:10

Prince John Wesley


Use an ANSI-C quoted string $'string'

You need a backslash-escaped literal newline to get to sed. In bash at least, $'' strings will replace \n with a real newline, but then you have to double the backslash that sed will see to escape the newline, e.g.

echo "a,b" | sed -e $'s/,/\\\n/g' 

Note this will not work on all shells, but will work on the most common ones.

like image 40
Walter Mundt Avatar answered Oct 16 '22 23:10

Walter Mundt