Extract filename and extension in Bash

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

    $ F = "text file.test.txt"  
    $ echo ${F/*./}  
    txt  
    

    This caters for multiple dots and spaces in a filename, however if there is no extension it returns the filename itself. Easy to check for though; just test for the filename and extension being the same.

    Naturally this method doesn't work for .tar.gz files. However that could be handled in a two step process. If the extension is gz then check again to see if there is also a tar extension.

提交回复
热议问题