Search code examples
stringbashfilenames

Get extension of files in Bash


I am writing a script which will sort files by extensions. I know a method to do this by file's names. The problem is, that same files haven't got extension in their names. For example if I have file: file.txt there is no problem to get an extension by simple extension="${filename##*.}". But if file name is just filename this method doesn't work. Is there any other option to get extension of file and put it to variable in Bash script?


Solution

  • It seems that you are only asking how to put the file extension of a filename into a variable in bash, and you are not asking about the sorting part. To do so, the following brief script can print the extension of each file from a file list.

    #!/bin/sh
    filesInCurrentDir=`ls`
    for file in $filesInCurrentDir; do
        extention=`sed 's/^\w\+.//' <<< "$file"`
        echo "the extention for $file is: "$extention #for debugging
    done
    

    the variable that contains the extention of the current file analysed is called extention. The command sed 's/^\w\+.// matched any length of characters until the first dot found in the filename and then removes it. Therefore if there are multiple file extentions these would be all listed (e.g. file.txt -> get extention txt but file.odt.pdf -> get extention odt.pdf).

    EXAMPLE

    Current Folder content (this can be any space-separated list of files that you feed to the loop)

    aaab.png
    abra
    anme2.jpg
    cadabra
    file
    file.png
    file.txt
    loacker.png
    myText
    name.pdf
    rusty.jgp
    

    Result of script above:

    the extention of aaab.png is: png
    the extention of abra is: 
    the extention of anme2.jpg is: jpg
    the extention of cadabra is: 
    the extention of file is: 
    the extention of file.png is: png
    the extention of file.txt is: txt
    the extention of loacker.png is: png
    the extention of myText is: 
    the extention of name.pdf is: pdf
    the extention of rusty.jgp is: jgp
    

    In this way, files with no extension will result in the extension variable being empty.