Extract filename and extension in Bash

后端 未结 30 2733
野趣味
野趣味 2020-11-21 05:29

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\'.\'          


        
30条回答
  •  庸人自扰
    2020-11-21 06:18

    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 :

    • On the web at section "3.5.3 Shell Parameter Expansion"
    • In the bash manpage at section called "Parameter Expansion"

提交回复
热议问题