Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell UNIX:从空格分隔的字符串创建数组,同时忽略引号中的空格_Shell_Unix - Fatal编程技术网

Shell UNIX:从空格分隔的字符串创建数组,同时忽略引号中的空格

Shell UNIX:从空格分隔的字符串创建数组,同时忽略引号中的空格,shell,unix,Shell,Unix,我试图从一个以空格分隔的字符串创建一个数组,这很好,直到我不得不忽略双引号中的空格来分割字符串 我试过: 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 当我真正想要它的时候

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

我试过:

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

这是特定于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

这会专门打断任意空格上的单词,但会与单个空格连接,因此引号中的自定义空格将丢失。

这是特定于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

这会专门打断任意空格上的单词,但会与单个空格连接,因此引号中的自定义空格将丢失。

您的
awk
在这里基本上是不可用的。没有它,您将得到类似的结果。您的
awk
在这里基本上是不可用的。没有它,你会得到类似的结果。