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
将失败(以及我到目前为止发现的任何其他脚本,即使在dup question中):
xargs: unmatched double quote; by default quotes are special to xargs unless you use the -0 option
但是这个输入是合法的,因为你可以输入命令行:
echo "a\"b" c
运行良好。所以这是行为不匹配而非非法输入。
答案 0 :(得分:0)
$ eval "a=($(cat data.in))"
$ for i in "${a[@]}";do echo "|$i|";done
|a|
|b|
|c|
|d e|
$