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"]
asked Jun 1 by anonymous

1 Answer

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
answered Aug 14 by Eric Z Ma (43,600 points)
edited Aug 18 by Eric Z Ma

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...