Linux: remove file extensions for multiple files

后端 未结 9 1927
甜味超标
甜味超标 2020-12-04 16:43

I have many files with .txt extension. How to remove .txt extension for multiple files in linux?

I found that

rename .old .new *.old
<
9条回答
  •  眼角桃花
    2020-12-04 17:08

    In case it helps, here's how I do it with zsh:

    for f in ./**/*.old; do
        mv "${f}" "${f%.old}"
    done
    

    The ${x%pattern} construct in zsh removes the shortest occurence of pattern at the end of $x. Here it is abstracted as a function:

    function chgext () {
        local srcext=".old"
        local dstext=""
        local dir="."
    
        [[ "$#" -ge 1 ]] && srcext="$1"
        [[ "$#" -gt 2 ]] && dstext="$2" dir="$3" || dir="${2:-.}"
    
        local bname=''
        for f in "${dir}"/**/*"${srcext}"; do
            bname="${f%${srcext}}"
            echo "${bname}{${srcext} → ${dstext}}"
            mv "${f}" "${bname}${dstext}"
        done
    }
    

    Usage:

    chgext
    chgext src
    chgext src dir
    chgext src dst dir
    
    Where `src` is the extension to find (default: ".old")
          `dst` is the extension to replace with (default: "")
          `dir` is the directory to act on (default: ".")
    

提交回复
热议问题