Prefix and postfix elements of a bash array

前端 未结 5 1772
-上瘾入骨i
-上瘾入骨i 2020-12-14 16:13

I want to pre- and postfix an array in bash similar to brace expansion.

Say I have a bash array

ARRAY=( one two three )

I want to b

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 16:21

    For arrays:

    ARRAY=( one two three )
    (IFS=,; eval echo prefix_\{"${ARRAY[*]}"\}_suffix)
    

    For strings:

    STRING="one two three"
    eval echo prefix_\{${STRING// /,}\}_suffix
    

    eval causes its arguments to be evaluated twice, in both cases first evaluation results in

    echo prefix_{one,two,three}_suffix
    

    and second executes it. For array case subshell is used to avoid overwiting IFS

    You can also do this in zsh:

    echo ${${ARRAY[@]/#/prefix_}/%/_suffix}
    

提交回复
热议问题