How to split a string by string in Bash?
Posted on In QAHow 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