使用bash将字符串转换为数组,遵循引号进行分组[复制]

参见英文答案 > Bash doesn’t parse quotes when converting a string to arguments4个
我有一个字符串:
Str='This string has "a substring"'

该字符串有逗号,所以如果我打印字符串,我看到:

echo "${Str}"

This string has "a substring".

如果我输入命令:

$Tmp=( ${Str} )
$echo "${Tmp[3]}"
"a
$echo "${Tmp[4]}"
Substring"

我喜欢打印:子串
任何建议?
我可以更改逗号,但必须将它从Str打印到Tmp

此问题需要使用xargs(它将引用的字符串保留在一起):
$Str='This string has "a substring"'
$IFS=$'\n' arr=( $(xargs -n1 <<<"$Str") )
$printf '<%s>\n' "${arr[@]}"
<This>
<string>
<has>
<a substring>

所以,你需要的元素:

$echo "${Tmp[3]}"
a substring

请注意,对于“未加引号”的项目,将删除前导或尾随空格:

$Str='  This    string    has "   a substring  "'
$IFS=$'\n' arr=( $(xargs -n1 <<<"$Str") )
$printf '<%s>\n' "${arr[@]}"
<This>
<string>
<has>
<   a substring  >

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...