Looking for a way to create an bash array based on a regex in filtering a directory.
For example I do:
A. local -a arr=( "$1"/* ); arr=( "${arr[@]##*/} );
- Creates array of all contents of the path sent in $1.
B. local -a arr=( "$1"/*"$2" ); arr=( "${arr[@]##*/}" );
- Creates array on filter expression in $2.
(I do not know why the * is not showing up in "$1"/*"$2"
in B. If I put 2 **s both show up!)
But it only works for a simple expression: example '.pub' - lists all public keys.
However if I send 'z.*.zip'to find all zip files beginning with 'z.' does not work.
I even tried taking out the *"$2"
in arr=( "$1"/*"$2" )
.
*"$2"
not showing up!
Your help would be much appreciated.
Thank you.
Globs don't expand in double quotes. You have to unquote it:
local -a arr=( "$1"/*$2 );
To avoid issues with whitespace, you can use IFS=""
first to inhibit word splitting while still doing glob expansion on unquoted variables.
Here's an example invocation:
$ cat script
foo() {
local -a arr=( "$1"/*$2 );
echo "Matching files: " "${arr[@]}"
}
foo "." "z.*.zip"
$ ls
lobsters.png pelican.zip script z.bar.zip z.cow.txt
$ bash script
Matching files: ./z.bar.zip
$