Extract filename and extension in Bash

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

    How to extract the filename and extension in fish:

    function split-filename-extension --description "Prints the filename and extension"
      for file in $argv
        if test -f $file
          set --local extension (echo $file | awk -F. '{print $NF}')
          set --local filename (basename $file .$extension)
          echo "$filename $extension"
        else
          echo "$file is not a valid file"
        end
      end
    end
    

    Caveats: Splits on the last dot, which works well for filenames with dots in them, but not well for extensions with dots in them. See example below.

    Usage:

    $ split-filename-extension foo-0.4.2.zip bar.tar.gz
    foo-0.4.2 zip  # Looks good!
    bar.tar gz  # Careful, you probably want .tar.gz as the extension.
    

    There's probably better ways to do this. Feel free to edit my answer to improve it.


    If there's a limited set of extensions you'll be dealing with and you know all of them, try this:

    switch $file
      case *.tar
        echo (basename $file .tar) tar
      case *.tar.bz2
        echo (basename $file .tar.bz2) tar.bz2
      case *.tar.gz
        echo (basename $file .tar.gz) tar.gz
      # and so on
    end
    

    This does not have the caveat as the first example, but you do have to handle every case so it could be more tedious depending on how many extensions you can expect.

提交回复
热议问题