J Szum
J Szum

Reputation: 515

Iterate over files and exclude the ones with certain name pattern Shell

How to iterate over files in the current directory and exclude some files having specific name patters? The solution must be POSIX compatible.

Assume the files to exclude follow the patterns: test[0-9].txt and work-.* (using regex).

The code I have so far:

for file in * 
do 
    if test "$file" != "test[0-9].txt" -o "$file" != "work-.*"
    then 
        echo "$file"
    fi 
done 

At the moment the output is all files in the working directory. I'm pretty sure pattern matching in test is incorrect, but how can I fix it?

Upvotes: 0

Views: 130

Answers (2)

georgexsh
georgexsh

Reputation: 16624

[[ is for bash, for POSIX shell, I guess case could do the glob style matching for you:

for file in *
do
    case $file in
        test[0-9].txt | work-*) ;;
        *) echo "$file";;
    esac
done

Upvotes: 2

Bohemian
Bohemian

Reputation: 424973

I think you want:

if ! [[ "$file" =~ "test[0-9].txt" ]] -a ! [[ "$file" =~ "work-.*" ]]

Upvotes: 0

Related Questions