Extract filename and extension in Bash

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

    You can force cut to display all fields and subsequent ones adding - to field number.

    NAME=`basename "$FILE"`
    EXTENSION=`echo "$NAME" | cut -d'.' -f2-`
    

    So if FILE is eth0.pcap.gz, the EXTENSION will be pcap.gz

    Using the same logic, you can also fetch the file name using '-' with cut as follows :

    NAME=`basename "$FILE" | cut -d'.' -f-1`
    

    This works even for filenames that do not have any extension.

提交回复
热议问题