I'm trying to list files using filters in a shell bash.
This example works:
result=$(ls *{A1,A2}*.txt)
echo $result
file1_A1.txt,file2_A2.txt
But when puuting the filters into a variable, it doesn't work:
filter={A1,A2}
result=$(ls *"$filter"*.txt)
echo $result
ls: cannot access '{A1,A2}': No such file or directory
I'm using a wrong sintax. How can I fix it?
Best
CodePudding user response:
Using extended globbing :
shopt -s extglob
filter="A1|A2"
result=(*@($filter)*.txt)
echo "${result[@]}"
CodePudding user response:
You could use eval
to achieve what you want (although I'm not a big fan of it; eval
should be avoided whenever possible IMO):
filter="{A1,A2}"
result=$(eval "ls *$filter*.txt")
echo "$result"
There is no other way as brace expansion is done before any other expansion (e.g. variable expansion). See man bash
, sections EXPANSION
and Brace Expansion
.
However, a possible workaround is given in this answer.