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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12744031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:47:51  来源:igfitidea点击:

How to change values of bash array elements without loop

arraysbash

提问by saloua

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.

提前致谢。

回答by choroba

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. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. 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.

${参数/模式/字符串}

模式替换。模式被扩展以产生一个模式,就像在路径名扩展中一样。参数被扩展,并且模式与其值的最长匹配被替换为字符串。如果模式以 / 开头,则模式的所有匹配项都将替换为字符串。通常只替换第一个匹配项。如果模式以# 开头,则它必须匹配参数扩展值的开头。如果模式以 % 开头,则它必须匹配参数扩展值的末尾。如果 string 为空,则删除模式的匹配项,并且可以省略 / 后面的模式。如果参数是@或*,则依次对每个位置参数应用替换操作,扩展是结果列表。如果参数是一个带有@或*下标的数组变量,则对数组中的每个成员依次进行替换操作,展开的就是结果列表。

回答by socketpair

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...

我不知道如何使用短代码消除这个问题......