1

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.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
mono-dr
  • 217
  • 1
  • 2
  • 9
  • Your question needs more clarification. What's the value of `$2`? And what are the files you intend to match it with? – konsolebox Aug 11 '14 at 18:45

1 Answers1

1

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

$
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • 2
    But he says all files beginning with `z.`. – konsolebox Aug 11 '14 at 18:47
  • Great! Thanks 'other guy'!New to stackoverflow. How do I close this question? – mono-dr Aug 11 '14 at 18:59
  • By they when you say Glob you mean all regex? When do I use IFS then? – mono-dr Aug 11 '14 at 19:00
  • If this solves your problem, there's a ✔ checkmark next to the answer you can click to accept it. – that other guy Aug 11 '14 at 19:01
  • Globs and regex look similar and are used for similar things, but they're not the same. `z.*.zip` is a glob and should not be quoted so that the shell will expand it. Tools like `grep` instead use regex (e.g. `z\..*\.zip`) and these should be quoted so the shell passes it straight to grep. – that other guy Aug 11 '14 at 19:04