Using sed to split a string with a delimiter

LinuxBashSedString Split

Linux Problem Overview


I have a string in the following format:

string1:string2:string3:string4:string5

I'm trying to use sed to split the string on : and print each sub-string on a new line. Here is what I'm doing:

cat ~/Desktop/myfile.txt | sed s/:/\\n/

This prints:

string1
string2:string3:string4:string5

How can I get it to split on each delimiter?

Linux Solutions


Solution 1 - Linux

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 global 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.

Solution 2 - Linux

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

Solution 3 - Linux

Using simply [tag:tr] :

$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

If you really need [tag:sed] :

$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

Solution 4 - Linux

This might work for you (GNU sed):

sed 'y/:/\n/' file

or perhaps:

sed y/:/$"\n"/ file

Solution 5 - Linux

This should do it:

cat ~/Desktop/myfile.txt | sed s/:/\\n/g

Solution 6 - Linux

If you're using gnu sed then you can use \x0A for newline:

sed 's/:/\x0A/g' ~/Desktop/myfile.txt

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhax0r_n_codeView Question on Stackoverflow
Solution 1 - LinuxfedorquiView Answer on Stackoverflow
Solution 2 - LinuxEd MortonView Answer on Stackoverflow
Solution 3 - LinuxGilles QuenotView Answer on Stackoverflow
Solution 4 - LinuxpotongView Answer on Stackoverflow
Solution 5 - LinuxJiminionView Answer on Stackoverflow
Solution 6 - LinuxanubhavaView Answer on Stackoverflow