Extract filename and extension in Bash

后端 未结 30 1963
野趣味
野趣味 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:19

    I think that if you just need the name of the file, you can try this:

    FULLPATH=/usr/share/X11/xorg.conf.d/50-synaptics.conf
    
    # Remove all the prefix until the "/" character
    FILENAME=${FULLPATH##*/}
    
    # Remove all the prefix until the "." character
    FILEEXTENSION=${FILENAME##*.}
    
    # Remove a suffix, in our case, the filename. This will return the name of the directory that contains this file.
    BASEDIRECTORY=${FULLPATH%$FILENAME}
    
    echo "path = $FULLPATH"
    echo "file name = $FILENAME"
    echo "file extension = $FILEEXTENSION"
    echo "base directory = $BASEDIRECTORY"
    

    And that is all =D.

提交回复
热议问题