How to expand bash array in path like brace expansion?

592 Views Asked by At

I have the following directory structure

./a/unknown.txt
./b/unknown.txt

What I want to achieve is

cat {a,b}/*.txt

The problem is I don't know a and b in advance but rather I have them in an array like so

dirs=(a b)

Now, I'm trying cat ${dirs[@]}/*.txt but it doesn't work. I have also tried other variations of this without success. The closest I have got is cat ${dirs[@]/%//*.txt} but this doesn't expand the *. Adding eval in the beginning fixes things but I feel there needs to be a more clever way.

I know I can iterate thorugh dirs and achieve what I want but I'm not interested in this solution.

2

There are 2 best solutions below

0
Criminal_Affair_At_SO On
#!/bin/bash

dirs=(a b)

shopt -s extglob

ls @(`echo ${dirs[@]} | tr ' ' '|'`)/*
0
user1934428 On

If you have them in an array, why don't you iterate over the array, which would be clearest:

for f in "${dirs[@]}"
do
  cat "$f"/*.txt
done

If you really distaste loops (why?) you could do it with a single command:

find "${dirs[@]}" -maxdepth 1 -name '*.txt'  -exec cat {} \;