While I think Glenn Jackman's answer is one of the nicest I've seen in a while, if you really do need to use a regex, then pathname expansion in an array won't work for you. Instead, you can either use find
to find files (and populate your array), or you can step through a directory and use the regex matching built in to bash.
First strategy, using find
(per Greg's BashFAQ/020):
unset files i
while IFS= read -r -d $'\0' file; do
files[i++]="$file"
done < <(find -E ./ -type f -regex '\./[0-9]{10}' -print0)
Note that find
's -regex
has implicit ^
and $
anchors. I'm using -E
to tell find
that I want to use ERE instead of BRE (which works in macOS, FreeBSD, other BSDs...). In Linux, you may want to use the -regextype
option ... or just express yourself in BRE.
Then select just the first 100 array items as Glenn suggested:
cp "${files[@]:0:100}" /path/to/destination/
The second strategy, using Bash's built-in regex support, might be done with a bit of scripting:
unset n
for file in *; do
[[ $file =~ ^[0-9]{10}$ ]] &&
mv -v "$file" dest/ &&
(( ++n >= 100 )) && break
done
This uses globbing to identify all files, and then for each one that matches your regex, it moves the file and increments a counter. The increment also checks to see if it's exceeded your threshold and if so, breaks out of the loop.
You could make it a one-liner if you like. I did when writing and testing it. And this could of course be written longer if you don't like your scripts terse. :)