Extract filename and extension in Bash

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

    You can use the magic of POSIX parameter expansion:

    bash-3.2$ FILENAME=somefile.tar.gz
    bash-3.2$ echo "${FILENAME%%.*}"
    somefile
    bash-3.2$ echo "${FILENAME%.*}"
    somefile.tar
    

    There's a caveat in that if your filename was of the form ./somefile.tar.gz then echo ${FILENAME%%.*} would greedily remove the longest match to the . and you'd have the empty string.

    (You can work around that with a temporary variable:

    FULL_FILENAME=$FILENAME
    FILENAME=${FULL_FILENAME##*/}
    echo ${FILENAME%%.*}
    

    )


    This site explains more.

    ${variable%pattern}
      Trim the shortest match from the end
    ${variable##pattern}
      Trim the longest match from the beginning
    ${variable%%pattern}
      Trim the longest match from the end
    ${variable#pattern}
      Trim the shortest match from the beginning
    

提交回复
热议问题