How to split a string by string in Bash?

How to split a string by string in Bash? For example,

"a string   separated by space" =>
["a", "string", "separated", "by", "space"]

and

"a,string,separated,by,comma" =>
["a", "string", "separated", "by", "comma"]

You can convert a string to an array using the grammar like

inarr=(${a})

If the delimiter is not space and delimiter is a single character or a string consisting of 1 or more of the characters, set the IFS like

IFS=',' inarr=(${a})

For the examples in the question:

For the space separated string:

$ a="a string   separated by space"
$ inarr=(${a})

Check the result:

$ echo ${inarr[@]}
a string separated by space

For the ‘,’ separated string, set the IFS:

$ a="a,string,separated,by,comma";
$ IFS=',' inarr=(${a});

Check the result:

$ echo ${inarr[@]}
a string separated by comma

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *