1

我正在尝试从空格分隔的字符串创建一个数组,这很好,直到我不得不忽略双引号内的空格来分割字符串。

我试过:

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,所以不知道如何解决它。谢谢

4

1 回答 1

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

这特别打破了任意空格上的单词,但与单个空格连接,因此引号内的自定义空格将丢失。

于 2013-07-04T13:22:16.380 回答