本文共 981 字,大约阅读时间需要 3 分钟。
bash 字符串分割
How to a by string in Bash? For example,
如何在Bash中按字符串 ? 例如,
"a string separated by" =>["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
翻译自:
bash 字符串分割
转载地址:http://hqowd.baihongyu.com/