我正在尝试从空格分隔的字符串创建一个数组,这个工作正常,直到我必须忽略双引号内的空格来分割字符串。
我试过:
inp='ROLE_NAME="Business Manager" ROLE_ID=67686'
arr=($(echo $inp | awk -F" " '{$1=$1; print}'))
这会将数组拆分为:
${arr[0]}: ROLE_NAME=Business
${arr[1]}: Manager
${arr[2]}: ROLE_ID=67686
实际上我想要它:
${arr[0]}: ROLE_NAME=Business Manager
${arr[1]}: ROLE_ID=67686
我对awk不是很好,所以无法弄清楚如何解决它。 感谢
答案 0 :(得分:1)
这是特定于bash的,可以使用ksh / zsh
inp='ROLE_NAME="Business Manager" ROLE_ID=67686'
set -- $inp
arr=()
while (( $# > 0 )); do
word=$1
shift
# count the number of quotes
tmp=${word//[^\"]/}
if (( ${#tmp}%2 == 1 )); then
# if the word has an odd number of quotes, join it with the next
# word, re-set the positional parameters and keep looping
word+=" $1"
shift
set -- "$word" "$@"
else
# this word has zero or an even number of quotes.
# add it to the array and continue with the next word
arr+=("$word")
fi
done
for i in ${!arr[@]}; do printf "%d\t%s\n" $i "${arr[i]}"; done
0 ROLE_NAME="Business Manager"
1 ROLE_ID=67686
这特别会破坏任意空格上的单词,但会与单个空格连接,因此引号内的自定义空格将会丢失。