一个bash数组preFIX和后缀元素 [英] Prefix and postfix elements of a bash array

查看:141
本文介绍了一个bash数组preFIX和后缀元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要pre型和Postfix类似括号扩展的bash的数组。

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

说我有一个bash数组

Say I have a bash array

ARRAY=( one two three )

我希望能够为pre型和后缀像下面的括号扩展

I want to be able to pre- and postfix it like the following brace expansion

echo prefix_{one,two,three}_suffix

我已经能够找到的最好的使用正则表达式的bash要么增加preFIX或后缀

The best I've been able to find uses bash regex to either add a prefix or a suffix

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

但我不能找到如何做一次两个东西。可能我可以使用正则表达式捕获并做类似

but I can't find anything on how to do both at once. Potentially I could use regex captures and do something like

echo ${ARRAY[@]/.*/prefix_$1_suffix}

但它似乎并不像捕捉在bash的变量正则表达式替换的支持。我还可以存储一个临时数组变量像

but it doesn't seem like captures are supported in bash variable regex substitution. I could also store a temporary array variable like

PRE=(${ARRAY[@]/#/prefix_})
echo ${PRE[@]/%/_suffix}

这可能是我能想到的最好的,但它似乎仍然分面值。最后一种选择是使用一个for循环类似于​​

This is probably the best I can think of, but it still seems sub par. A final alternative is to use a for loop akin to

EXPANDED=""
for E in ${ARRAY[@]}; do
    EXPANDED="prefix_${E}_suffix $EXPANDED"
done
echo $EXPANDED

但是这是超级难看。我也不知道我会得到它的工作,如果我想在任何地方场所的preFIX后缀或数组元素。

but that is super ugly. I also don't know how I would get it to work if I wanted spaces anywhere the prefix suffix or array elements.

推荐答案

您最后的循环可能会在空白友好的方式来实现与

Your last loop could be done in a whitespace-friendly way with:

EXPANDED=()
for E in "${ARRAY[@]}"; do
    EXPANDED+=("prefix_${E}_suffix")
done
echo "${EXPANDED[@]}"

这篇关于一个bash数组preFIX和后缀元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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