I have two bash arrays, and I want to append array strings to the end of the name array elements.
array=(a b c)
name=(toto_ tata_)
result :
toto_a
toto_b
toto_c
tata_a
tata_b
tata_c
I tried those command :
for i in "${name[@]}"
do
arra=( "${i/%/$array[@]}" )
done
printf '%s\n' "${arra[@]}"
CodePudding user response:
Using Brace Expansion to expand as a cross-product
readarray -t new_array < <(IFS=,; eval "printf '%s\n' {${name[*]}}{${array[*]}}")
# ....................................................^..........^^...........^
then
$ declare -p new_array
declare -a new_array=([0]="toto_a" [1]="toto_b" [2]="toto_c" [3]="tata_a" [4]="tata_b" [5]="tata_c")
Eval is necessary to allow the variable expansion to occur first, then perform the brace expansion second.
CodePudding user response:
I'd recommend using a second for
:
array=(a b c)
name=(toto_ tata_)
arra=()
for i in "${name[@]}"; do
for j in "${array[@]}"; do
arra =("$i$j")
done
done
printf '%s\n' "${arra[@]}"
Will produce:
toto_a
toto_b
toto_c
tata_a
tata_b
tata_c
CodePudding user response:
Second for
could be avoided by Parameter expansion
for nam in "${name[@]}";do printf "${nam/%/%s\\n}" "${array[@]}";done
will produce:
toto_a
toto_b
toto_c
tata_a
tata_b
tata_c
For fun, some variants (without any for
loop):
printf -v fmt "${name[*]/%/%%s\\n}"
printf "${fmt// }" ${array[@]}
toto_a
tata_b
toto_c
tata_
or
printf -v fmt "${name[*]/%/%%s\\n}";printf "${fmt// }" ${array[@]}{,}
toto_a
tata_b
toto_c
tata_a
toto_b
tata_c
then without for
, but with a fork to sort
printf -v fmt "${name[*]/%/%%s\\n}";printf "${fmt// }" ${array[@]}{,} |
sort -k 1r,1.5
toto_a
toto_b
toto_c
tata_a
tata_b
tata_c