Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top