Extract filename and extension in Bash

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

    pax> echo a.b.js | sed 's/\.[^.]*$//'
    a.b
    pax> echo a.b.js | sed 's/^.*\.//'
    js
    

    works fine, so you can just use:

    pax> FILE=a.b.js
    pax> NAME=$(echo "$FILE" | sed 's/\.[^.]*$//')
    pax> EXTENSION=$(echo "$FILE" | sed 's/^.*\.//')
    pax> echo $NAME
    a.b
    pax> echo $EXTENSION
    js
    

    The commands, by the way, work as follows.

    The command for NAME substitutes a "." character followed by any number of non-"." characters up to the end of the line, with nothing (i.e., it removes everything from the final "." to the end of the line, inclusive). This is basically a non-greedy substitution using regex trickery.

    The command for EXTENSION substitutes a any number of characters followed by a "." character at the start of the line, with nothing (i.e., it removes everything from the start of the line to the final dot, inclusive). This is a greedy substitution which is the default action.

提交回复
热议问题