Julio
Julio

Reputation: 23

Listing files using a variable filter

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

Upvotes: 1

Views: 357

Answers (2)

Fonic
Fonic

Reputation: 2955

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 probably no other way if you insist on using braces 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.

Upvotes: 0

Philippe
Philippe

Reputation: 26422

Using extended globbing :

shopt -s extglob

filter="A1|A2"
result=(*@($filter)*.txt)
echo "${result[@]}"

Upvotes: 2

Related Questions