Leon S. Kennedy
Leon S. Kennedy

Reputation: 79

How to check if a file has an extension (any extension) with regular expression in Bash?

I am new to Bash Scripting using Ubuntu18.04 and trying to find if a file has an extension (any extension) but the regular expression I am trying to implement is not working. I have been using the same regular expression in Perl script and it is working fine. But it does not work in Bash Script. Below is my Bash Code:

dir="ImageFolder"
fileName=""
for f in "$dir"/*;
do
    fileName="$(basename "$f")"

if [[ $fileName =~ /(.*)?\.(.*)/ ]]
then
    echo $fileName
    echo "Yes it has extension"
fi
done

It does not execute those echo commands even though the files inside "ImageFolder" has their extensions. In other words, the "if" statement is not executing. It only gets executed when I invert the condition by placing a '!' symbol before '$fileName'. When I invert the condition: if [[ ! $fileName =~ /(.*)?\.(.*)/ ]] then it executes but gives undesired outputs (Please See Image): It displays files with extension and says yes it has extension

But when I actually remove file extensions by going physically inside the folder then again it executes and says file extension exists (Please see image) Says 'Yes It has extensions even though I've removed them'

I really need this regular expression to work. Some help will be highly appreciated.

Upvotes: 2

Views: 3549

Answers (1)

magesh
magesh

Reputation: 111

It should work once you remove the '/' surrounding the regex pattern.

[[ $fileName =~ (.*)?\.(.*) ]]

ref. https://www.tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF for more examples.

Upvotes: 1

Related Questions