简体   繁体   English

如何在没有循环的情况下更改bash数组元素的值

[英]How to change values of bash array elements without loop

array=(a b c d)

I would like to add a character before each element of the array in order to have this 我想在数组的每个元素之前添加一个字符,以便拥有它

array=(^a ^b ^c ^d)

An easy way to do that is to loop on array elements and change values one by one 一种简单的方法是循环数组元素并逐个更改值

for i in "${#array[@]}"
do
    array[i]="^"array[i]
done

But I would like to know if there is any way to do the same thing without looping on the array as I have to do the same instruction on all elements. 但我想知道是否有任何方法可以在没有循环数组的情况下做同样的事情,因为我必须对所有元素执行相同的指令。

Thanks in advance. 提前致谢。

Use Parameter Expansion: 使用参数扩展:

array=("${array[@]/#/^}")

From the documentation: 从文档:

${parameter/pattern/string} $ {参数/模式/字符串}

Pattern substitution. 模式替换。 The pattern is expanded to produce a pattern just as in pathname expansion. 扩展模式以生成模式,就像在路径名扩展中一样。 Parameter is expanded and the longest match of pattern against its value is replaced with string. 扩展参数,并将模式与其值的最长匹配替换为字符串。 If pattern begins with /, all matches of pattern are replaced with string. 如果pattern以/开头,则pattern的所有匹配都将替换为string。 Normally only the first match is replaced. 通常只替换第一场比赛。 If pattern begins with #, it must match at the beginning of the expanded value of parameter. 如果pattern以#开头,则它必须在参数的扩展值的开头匹配。 If pattern begins with %, it must match at the end of the expanded value of parameter. 如果pattern以%开头,则它必须在参数的扩展值的末尾匹配。 If string is null, matches of pattern are deleted and the / following pattern may be omitted. 如果string为null,则删除pattern的匹配,并且可以省略/ following模式。 If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. 如果参数是@或*,则替换操作依次应用于每个位置参数,并且扩展是结果列表。 If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list. 如果parameter是使用@或*下标的数组变量,则替换操作依次应用于数组的每个成员,并且扩展是结果列表。

This way also honor whitespaces in array values: 这种方式也尊重数组值中的空格:

array=( "${array[@]/#/^}" )

Note, this will FAIL if array was empty and you set previously 注意,如果数组为空并且您先前已设置,则这将失败

set -u

I don't know how to eliminate this issue using short code... 我不知道如何使用短代码消除这个问题...

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

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