Extract filename and extension in Bash

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

    A simple answer:

    To expand on the POSIX variables answer, note that you can do more interesting patterns. So for the case detailed here, you could simply do this:

    tar -zxvf $1
    cd ${1%.tar.*}
    

    That will cut off the last occurrence of .tar..

    More generally, if you wanted to remove the last occurrence of .. then

    ${1.*.*}
    

    should work fine.

    The link the above answer appears to be dead. Here's a great explanation of a bunch of the string manipulation you can do directly in Bash, from TLDP.

提交回复
热议问题