bash 字符串分割
How to split a string by string in Bash? For example,
"a string separated byspace" =>
["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
如果定界符不是空格,并且定界符是单个字符或由1个或多个字符组成的字符串 ,则将IFS
设置为
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
:
对于以','分隔的字符串,设置IFS
:
$ a="a,string,separated,by,comma";
$ IFS=',' inarr=(${a});
Check the result:
检查结果:
$ echo ${inarr[@]}
a string separated by comma
Answered by Eric Z Ma.
埃里克·马(Eric Z Ma)回答。
翻译自: https://www.systutorials.com/how-to-split-a-string-by-string-in-bash/
bash 字符串分割