简体   繁体   English

bash而数组包含空间

[英]bash while array containing space

I got the following code. 我得到以下代码。 I would like to make cc dd ee ff as array [2] 我想将cc dd ee ff作为数组[2]

    keyvariable="aa bb cc dd ee ff"
    while read -a line;
    do
       a=$(echo "${line[0]}")
       b=$(echo "${line[1]}")
       c=$(echo "${line[2]}")
    done <<< "$keyvariable" 
    echo "$a $b $c"

current output: 当前输出:

      aa bb cc   

I would like to have the following output, where aa is [0] bb is [1] and cc dd ee is [2] 我想要以下输出,其中aa是[0] bb是[1]而cc dd ee是[2]

      aa bb cc dd ee

You don't need the while loop here at all. 您根本不需要在这里的while循环。

You don't want to use read with the -a switch at all here. 您根本不想在-a开关中使用read Instead you want: 相反,您想要:

read -r a b c <<< "$keyvariable"

In this case, read will split the (first line of the) expansion of the variable keyvariable on the spaces, but only for the first and second fields (these will go in variables a and b ) and the remaining part will go in c . 在这种情况下, read将在空间上拆分变量keyvariable的(的第一行)扩展,但仅适用于第一和第二字段(这些将进入变量ab ),其余部分将进入c The -r switch is used in case you have backslashes in your string; -r开关用于字符串中有反斜杠的情况; without this, backslashes would be treated as an escape character. 否则,反斜杠将被视为转义字符。

gniourf_gniourf's answer is absolutely correct, however if you don't know how many fields you are going to have or need to select your "prefix" fields based on some other criteria then using an array and Substring Expansion (which is a bad name for this usage of it but that's what it is called) can let you do that. gniourf_gniourf的答案是绝对正确的,但是,如果您不知道将要拥有多少个字段,或者是否需要根据其他条件选择“前缀”字段,则可以使用数组和Substring Expansion (这是一个不好的名字用法,但这就是所谓的用法)可以让您做到这一点。

$ keyvariable="aa bb cc dd ee ff"
$ read -a line <<<"$keyvariable"
$ a=${line[0]}
$ b=${line[1]}
$ c=${line[@]:2}
$ echo "$a"
aa
$ echo "$b"
bb
$ echo "$c"
cc dd ee ff

Also note the lack of $(echo ...) on the assignment lines. 还要注意分配行上缺少$(echo ...) You don't need it. 不用了

Just do 做就是了

a=( $keyvariable )

and you have array a with your values, so your example would be 并且您的值具有数组a ,因此您的示例将是

keyvariable="aa bb cc dd ee ff"
line=( $keyvariable ) # of course you can do it in the same line
a="${line[0]}"
b="${line[1]}"
n=$(( ${#line[@]} - 1))
unset line[$n]
echo "$a $b $c"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM