Extract filename and extension in Bash

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

    If you also want to allow empty extensions, this is the shortest I could come up with:

    echo 'hello.txt' | sed -r 's/.+\.(.+)|.*/\1/' # EXTENSION
    echo 'hello.txt' | sed -r 's/(.+)\..+|(.*)/\1\2/' # FILENAME
    

    1st line explained: It matches PATH.EXT or ANYTHING and replaces it with EXT. If ANYTHING was matched, the ext group is not captured.

提交回复
热议问题