Checking file names inside a directory with Regular Expressions

bashregex

I have a list of files inside a directory and I want to make a bash script which uses a regular expression to check if every file name inside it has this syntax:

xxxx_xxxx_xx_xx

Where x are numbers.

Edit: I only need with the regex

Best Answer

How about

#/usr/bin/env bash
for f in *
do
  [[ $f =~ [0-9]{4}_[0-9]{4}_[0-9]{2}_[0-9]{2} ]] || 
    echo "File $f does not match"
done

The regular expression checks for any digit ([0-9]). The numbers in curly braces are the number of repetitions so [0-9]{4} will match any 4 digits.

I would recommend you don't use bash for this but find instead. It will probably be faster, and it is certainly more portable (not all shells can deal with regular expressions):

find -regextype posix-egrep -not -regex '\./[0-9]{4}_[0-9]{4}_[0-9]{2}_[0-9]{2}'
Related Question