Extract filename and extension in Bash

后端 未结 30 2084
野趣味
野趣味 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条回答
  •  猫巷女王i
    2020-11-21 06:32

    Using example file /Users/Jonathan/Scripts/bash/MyScript.sh, this code:

    MY_EXT=".${0##*.}"
    ME=$(/usr/bin/basename "${0}" "${MY_EXT}")
    

    will result in ${ME} being MyScript and ${MY_EXT} being .sh:


    Script:

    #!/bin/bash
    set -e
    
    MY_EXT=".${0##*.}"
    ME=$(/usr/bin/basename "${0}" "${MY_EXT}")
    
    echo "${ME} - ${MY_EXT}"
    

    Some tests:

    $ ./MyScript.sh 
    MyScript - .sh
    
    $ bash MyScript.sh
    MyScript - .sh
    
    $ /Users/Jonathan/Scripts/bash/MyScript.sh
    MyScript - .sh
    
    $ bash /Users/Jonathan/Scripts/bash/MyScript.sh
    MyScript - .sh
    

提交回复
热议问题