Reputation: 2635
In a sh script, I am trying to loop over all files that match the following pattern
abc.123
basically abc. followed by only numbers, number following .
can be of any length.
Using
$ shopt -s extglob
$ ls abc.+([0-9])
does the job but on terminal and not through the script. How can I get only files that match the pattern?
Upvotes: 2
Views: 10808
Reputation: 123600
If you're using sh
and not bash
, and presumably you also want to be POSIX compliant, you can use:
for f in ./*
do
echo "$f" | grep -Eq '^\./abc.[0-9]+$' && continue
echo "Something with $f here"
done
It will work fine with filenames with spaces, quotes and such, but may match some filenames with line feeds in them that it shouldn't.
If you tagged your question bash
because you're using bash, then just use extglob like you described.
Upvotes: 1
Reputation: 195209
if I understood you right, the pattern could be translated into regex:
^abc\.[0-9]+$
so you could
keep using ls
and grep the output. for example:
ls *.*|xargs -n1|grep -E '^abc\.[0-9]+$'
or use find
find has an option -regex
Upvotes: 2