How to change values of bash array elements without loop

前端 未结 2 1526
谎友^
谎友^ 2020-12-01 04:11
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)
<         


        
相关标签:
2条回答
  • 2020-12-01 04:58

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

    0 讨论(0)
  • 2020-12-01 04:59

    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.

    0 讨论(0)
提交回复
热议问题