Get just the filename from a path in a Bash script

This question already has an answer here:

  • Extract filename and extension in Bash 35 answers

  • Most UNIX-like operating systems have a basename executable for a very similar purpose (and dirname for the path):

    pax> a=/tmp/file.txt
    pax> b=$(basename $a)
    pax> echo $b
    file.txt
    

    That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.

    So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.

    One way to do that (and this is a bash -only solution, needing no other executables):

    pax> a=/tmp/xx/file.tar.gz
    pax> xpath=${a%/*} 
    pax> xbase=${a##*/}
    pax> xfext=${xbase##*.}
    pax> xpref=${xbase%.*}
    pax> echo;echo path=${xpath};echo pref=${xpref};echo ext=${xfext}
    
    path=/tmp/xx
    pref=file.tar
    ext=gz
    

    That little snippet sets xpath (the file path), xpref (the file prefix, what you were specifically asking for) and xfext (the file extension).


    basename and dirname solutions are more convenient. Those are alternative commands:

    FILE_PATH="/opt/datastores/sda2/test.old.img"
    echo "$FILE_PATH" | sed "s/.*///"
    

    This returns test.old.img like basename .

    This is salt filename without extension:

    echo "$FILE_PATH" | sed -r "s/.+/(.+)..+/1/"
    

    It returns test.old .

    And following statement gives the full path like dirname command.

    echo "$FILE_PATH" | sed -r "s/(.+)/.+/1/"
    

    It returns /opt/datastores/sda2


    Here is an easy way to get the file name from a path:

    echo "$PATH" | rev | cut -d"/" -f1 | rev
    

    To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

    cut -d"." -f1
    
    链接地址: http://www.djcxy.com/p/57080.html

    上一篇: 如何在bash中检索文件名或扩展名

    下一篇: 从Bash脚本中的路径获取文件名