how to retrieve filename or extension within bash

This question already has an answer here:

  • Extract filename and extension in Bash 35 answers

  • 打印最后一个由非字母字符分隔的提交。

    awk -F '[^[:alpha:]]' '{ print $0,$NF }'
    /home/myuser/mydata/myfile/data.log log
    /home/myuser/mydata/myfile/myfile.gz gz
    /home/myuser/mydata/myfile/mod.conf conf
    /home/myuser/mydata/myfile/security security
    /home/myuser/mydata/myfile/last last
    

    这应该适合你:

    x='/home/myuser/mydata/myfile/security'
    ( IFS=[/.] && arr=( $x ) && echo ${arr[@]:(-1):1} )
    security
    
    x='/home/myuser/mydata/myfile/data.log'
    ( IFS=[/.] && arr=( $x ) && echo ${arr[@]:(-1):1} )
    log
    

    To extract the last element in a filename path:

    filename=$(path##*/}
    

    To extract characters after a dot in a filename:

    extension=${filename##*.}
    

    But (my comment) rather than looking at the extension, it might be better to use file . See man file .

    链接地址: http://www.djcxy.com/p/57082.html

    上一篇: 修整字符串中的字符串

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