How to remove extensions from name when looking in a FOR loop

This question already has an answer here:

  • Extract filename and extension in Bash 35 answers

  • To remove the extension:

    filename_without_ext="${file%.*}"
    

    It means, remove shortest suffix that begins with a dot.

    Then check if the archive exists with something like

    if [ -e "$dir/$filename_without_ext.tar.bz2" ]; then
    

    I'm not entirely how it will achive safer delete, but this thing will do the trick, if you want to remove the extention, and search for tar.bz2 but beware if file name is text.something.txt will results text.tar.bz2

    FILE=test.txt; echo ${FILE/.*/.tar.bz2}
    

    there are other ways to reach same result using Variable Substitution :

  • ${var%pattern} Use value of var after removing text matching pattern from the right. Remove the shortest matching piece.
  • ${var%%pattern} Same as % pattern, but remove the longest matching piece.
  • ${var/pat/repl} Use value of var, with first match of pat re-placed with repl.
  • ${var/pat} Use value of var, with first match of pat deleted.
  • if you want to do some checking before rm ,

    alias rm='/usr/bin/rm -rfv'
    
    链接地址: http://www.djcxy.com/p/57102.html

    上一篇: 芹菜工人之间共享的XMPP连接

    下一篇: 如何在查找FOR循环时从名称中删除扩展名