如何在没有循环的情况下更改bash数组元素的值 [英] How to change values of bash array elements without loop

查看:45
本文介绍了如何在没有循环的情况下更改bash数组元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

提前致谢.

推荐答案

使用参数扩展:

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

来自文档:

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

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

这篇关于如何在没有循环的情况下更改bash数组元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆