Using sed to split a string with a delimiter
To split a string with a delimiter with GNU sed you say:
sed 's/delimiter/\n/g' # GNU sed
For example, to split using :
as a delimiter:
$ sed 's/:/\n/g' <<< "he:llo:you"
he
llo
you
Or with a non-GNU sed:
$ sed $'s/:/\\\n/g' <<< "he:llo:you"
he
llo
you
In this particular case, you missed the g
after the substitution. Hence, it is just done once. See:
$ echo "string1:string2:string3:string4:string5" | sed s/:/\\n/g
string1
string2
string3
string4
string5
g
stands for g
lobal and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.
All together, in your case you would need to use:
sed 's/:/\\n/g' ~/Desktop/myfile.txt
Note that you can directly use the sed ... file
syntax, instead of unnecessary piping: cat file | sed
.
Using \n
in sed
is non-portable. The portable way to do what you want with sed
is:
sed 's/:/\
/g' ~/Desktop/myfile.txt
but in reality this isn't a job for sed
anyway, it's the job tr
was created to do:
tr ':' '
' < ~/Desktop/myfile.txt