Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefix and postfix elements of a bash array

Tags:

arrays

regex

bash

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 be able to pre- and postfix it like the following brace expansion

echo prefix_{one,two,three}_suffix 

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} 

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.

like image 967
Erik Avatar asked Dec 04 '13 04:12

Erik


People also ask

Are there data structures in Bash?

Arrays are one of the most used and fundamental data structures. You can think of an array is a variable that can store multiple variables within it. In this article, we'll cover the Bash arrays, and explain how to use them in your Bash scripts.

What is the syntax to define array in Bash scripting?

Another note: Bash does not typically require curly braces for variables, but it does for arrays. So you will notice that when you reference an array, you do so with the syntax ${myArray} , but when you reference a string or number, you simply use a dollar sign: $i .

How do I add elements to an array in Bash?

To append element(s) to an array in Bash, use += operator. This operator takes array as left operand and the element(s) as right operand. The element(s) must be enclosed in parenthesis.

Are there arrays in shell script?

There are two types of arrays that we can work with, in shell scripts. The default array that's created is an indexed array. If you specify the index names, it becomes an associative array and the elements can be accessed using the index names instead of numbers.


1 Answers

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[@]}")" 
like image 119
Mingye Wang Avatar answered Sep 19 '22 21:09

Mingye Wang