Thursday, September 29, 2011

Replacing space with newline

There are a few ways to achieve that:

1. sed

$ echo "one two three" | sed 's/ /\n/g'
one
two
three
2. awk
$ echo "one two three" | awk '$1=$1' RS= OFS="\n"
one
two
three
3. tr
$ echo "one two three" | tr -s ' ' '\n'
one
two
three
3 ways to do it, have fun

2 comments:

BCL said...

Thks for post

a more generic space mgt with tr is to use label, it will work whatever is space or tab

echo "one two three" | tr -s '[:space:]' '\n'
one
two
three


a more generic char mgt with tr is to use octal

echo "one two three" | tr -s '\040' '\012'
one
two
three

an easy way to caych octal value is od

echo "one two three" | od -cto1
0000000 o n e t w o t h r e e \n
157 156 145 040 164 167 157 040 164 150 162 145 145 012
0000016

Anonymous said...

Just a heads up, the sed version won't work on a mac.

http://stackoverflow.com/questions/10748453/replace-comma-with-newline-in-sed