Thursday 22 December 2016

string - Extract filename and extension in Bash



I want to get the filename (without extension) and the extension separately.



The best solution I found so far is:



NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`



This is wrong because it doesn't work if the file name contains multiple . characters. If, let's say, I have a.b.js, it will consider a and b.js, instead of a.b and js.



It can be easily done in Python with



file, ext = os.path.splitext(path)


but I'd prefer not to fire up a Python interpreter just for this, if possible.



Any better ideas?



Answer



First, get file name without the path:



filename=$(basename -- "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"


Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:




filename="${fullfile##*/}"


You may want to check the documentation :




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...