Samuel Hulla
Samuel Hulla

Reputation: 7089

Is there a way to check whether there is any type of file extension included?

I am aware of how to check for file extensions, however what I'm asking is if there's a way to check whether the user input was include with any file extension in general.

for example

./myscript index.html is with file extension

Technically I know I could check for file extension using standard bash using something like

FILE="$1"
FILE_EXT=${FILE##.*}

However issue arrises when i would have a file named file.script.up.exe which has multiple dots and obviously it would end my file_ext on file.script which is not what I want.

Technically you could use FILE_EXT=$(echo "$FILE" | awk -F . '{print $NF}')

but then issue arises when the program would be launched without a file extension

So basically what I need is to create an if condition to check whether the script was launched with a file extension or not, and depending on the result of that if condition act accordingly

Any idea how to work around this?

Upvotes: 0

Views: 93

Answers (3)

clt60
clt60

Reputation: 63902

If understand right, you want only the last extension in case of multiple dots in the file, e.g. some.file.ext you want the ext.

This is usually simple, but here are corner cases too. For example the file .profile has no extension but has a dot. And like.

So, i would to use the not-so-short solution, maybe someone post you the better one.

    line="/some/full/path/name.to.file.ext"

    regex='^(.+)\.([^.]+)$'
    dir=$(dirname "$line")
    base=$(basename "$line")
    ext=""
    if [[ "$base" =~ $regex ]]
    then
            fnoex="${BASH_REMATCH[1]}"
            ext="${BASH_REMATCH[2]}"
    else
            fnoex="$base"
    fi
    #here you have 4x variables
    # $dir - directory name
    # $base - the filename
    # $fnoex - filename without the extension
    # $ext - the extension

The principe is:

  • you should first split the path to dirname and filename
  • and splitting only the filename (exlucing false matches on dots in directory names)

The above should work even for strange path&file names, like

/we.i.r d/.file    #no ext
.file.ext.         #no ext
./file.ext..ext2   #ext2

Upvotes: 0

ray_g
ray_g

Reputation: 46

awk should use like this in your case: check the number fields before print the last one.

FILE_EXT=$(echo "$FILE" | awk -F . '{if (NF>1) {print $NF}}')

Upvotes: 0

Fred
Fred

Reputation: 6995

Do this instead :

FILE="$1"
FILE_EXT=${FILE##*.}

The only change is the asterisk and dot are in reverse order compared to your code.

The ## expansion operator removes the longest match of the pattern starting from the beginning of the string contained in the variable. It is a pattern, not a regular expression, so * stands for any sequence of characters, and . stands for a literal period. The result is that this expansion removes everything up to and including the last period in the file name.

Upvotes: 2

Related Questions