data.in
:
a b c 'd e'
script.sh
:
while read -a arr; do
echo "${#arr[@]}"
for i in "${arr[@]}"; do
echo "$i"
done
done
命令:
cat data.in | bash script.sh
输出:
5
a
b
c
'd
e'
问题:
如何将'd e'
作为数组中的单个元素获取?
更新。这是我目前为止做得最好的:
while read line; do
arr=()
while read word; do
arr+=("$word")
done < <(echo "$line" | xargs -n 1)
echo "${#arr[@]}"
for i in "${arr[@]}"; do
echo "$i"
done
done
输出:
4
a
b
c
d e
然而,以下的
data.in
:"a\"b" c
它将失败(以及到目前为止我发现的任何其他脚本,甚至是在重复的问题中):
xargs: unmatched double quote; by default quotes are special to xargs unless you use the -0 option
但这个输入是合法的,因为你可以在命令行中输入:
echo "a\"b" c
它运行良好。因此,这是行为不匹配而不是非法输入。
xargs printf '%s\0'
将您的字符串解析为一个以 NUL 为分隔符的流,这样 bash 就可以无歧义地读取它了。(xargs
在不使用-d
或-0
扩展时,使用类似 shell 的解析规则将输入拆分成单词)。具体请参见:https://dev59.com/4l8e5IYBdhLWcg3wHXeJ#31485948。 - Charles Duffy-r
。在重复的答案中,该解决方案适用于不同的工作,并且似乎无法与此处的data.in
一起使用。我仍在测试代码,以查看是否存在其他可能导致其失败的边角情况。 - Cyker