bash 字符串分割_如何在Bash中按字符串分割字符串?

bash 字符串分割

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

如何在Bash中按字符串分割 字符串 ? 例如,

"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 字符串分割

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值