Find and replace filename recursively in a directory

前端 未结 14 1954
野趣味
野趣味 2020-11-28 21:24

I want to rename all the files in a folder which starts with 123_xxx.txt to xxx.txt.

For example, my directory has:

123_xxx         


        
14条回答
  •  -上瘾入骨i
    2020-11-28 22:01

    You can make a little bash script for that. Create a file named recursive_replace_filename with this content :

    #!/bin/bash
    
    if test $# -lt 2; then
      echo "usage: `basename $0`  "
    fi
    
    for file in `find . -name "*$1*" -type f`; do
      mv "'$file'" "${file/'$1'/'$2'}"
    done
    

    Make executable an run:

    $ chmod +x recursive_replace_filename
    $ ./recursive_replace_filename 123_ ""
    

    Keep note that this script can be dangerous, be sure you know what it's doing and in which folder you are executing it, and with which arguments. In this case, all files in the current folder, recursively, containing 123_ will be renamed.

提交回复
热议问题