Extract filename and extension in Bash

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

    You could use the cut command to remove the last two extensions (the ".tar.gz" part):

    $ echo "foo.tar.gz" | cut -d'.' --complement -f2-
    foo
    

    As noted by Clayton Hughes in a comment, this will not work for the actual example in the question. So as an alternative I propose using sed with extended regular expressions, like this:

    $ echo "mpc-1.0.1.tar.gz" | sed -r 's/\.[[:alnum:]]+\.[[:alnum:]]+$//'
    mpc-1.0.1
    

    It works by removing the last two (alpha-numeric) extensions unconditionally.

    [Updated again after comment from Anders Lindahl]

提交回复
热议问题