bash 数组的前缀和后缀元素 [英] Prefix and postfix elements of a bash array

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

问题描述

我想在 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 )

我希望能够像下面的大括号扩展一样前置和后缀

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

echo prefix_{one,two,three}_suffix

我能找到的最好的使用 bash regex 添加前缀或后缀

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}

这可能是我能想到的最好的,但它似乎仍然低于标准.最后一种选择是使用类似于

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

但这太丑了.如果我想在前缀后缀或数组元素的任何地方使用空格,我也不知道如何让它工作.

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.

推荐答案

Bash 大括号扩展不使用正则表达式.使用的模式只是一些 shell glob,您可以在 bash 手册中找到它 3.5.8.1 模式匹配.

Bash brace expansion don't use regexes. The pattern used is just some shell glob, which you can find in bash manual 3.5.8.1 Pattern Matching.

你的两步解决方案很酷,但为了空格安全需要一些引号:

Your two-step solution is cool, but it needs some quotes for whitespace safety:

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

你也可以用一些邪恶的方式来做:

You can also do it in some evil way:

eval "something $(printf 'pre_%q_suf ' "${ARRAY[@]}")"

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

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