Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed to split a string with a delimiter

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?

like image 912
hax0r_n_code Avatar asked Aug 14 '13 14:08

hax0r_n_code


People also ask

How do I split a string on a delimiter in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

Can you use sed on a string?

The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.

How do you separate text in Linux?

To split a file into pieces, you simply use the split command. By default, the split command uses a very simple naming scheme. The file chunks will be named xaa, xab, xac, etc., and, presumably, if you break up a file that is sufficiently large, you might even get chunks named xza and xzz.


1 Answers

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.

like image 153
fedorqui 'SO stop harming' Avatar answered Oct 11 '22 09:10

fedorqui 'SO stop harming'