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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With