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
,它運行良好。所以這是行爲不合法的輸入不匹配。
這裏的正確答案是使用'xargs printf'%s \ 0''來解析你的字符串爲一個NUL-delimited流,該bash可以毫不含糊地讀取。 ('xargs',當不使用'-d'或'-0'擴展名時,使用類似shell的解析規則將輸入拆分爲單詞)。具體來說,請參閱http://stackoverflow.com/a/31485948/14122 –
我認爲這個問題在MCVE中表達問題的效果要好於它所鏈接的副本。 +1。另外,查爾斯,Tim Toady。如果這個問題仍然對您的答案不滿意,我會建議採用不同的途徑。 – ghoti
@ ghoti,呃?我沒有在這裏提供任何答案(只有一條評論,並且你完全能夠提供你自己的答案),並且鏈接的問題*已打開。我很樂意在那裏看到另一個正確的答案。 –