Find and replace filename recursively in a directory

前端 未结 14 1778
野趣味
野趣味 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条回答
  • 2020-11-28 21:58
    prename s/^123_// 123_*
    

    See prename in the official Perl5 wiki. Copy for your convenience:

    prename - A script that renames files according to a regular expression. (Where was the original published?) Originally named rename, it is found mostly as prename because the original one clashes with the rename command from the util-linux package. Numerous forks and reimplementations:

    • http://search.cpan.org/dist/rename/
    • http://search.cpan.org/dist/pbr/
    • http://search.cpan.org/dist/File-Rename/
    • http://search.cpan.org/dist/File-PerlMove/
    • http://search.cpan.org/dist/App-FileTools-BulkRename/
    • http://search.cpan.org/dist/App-perlmv/
    • http://training.perl.com/scripts/rename
    • https://github.com/msabramo/ren-regexp
    0 讨论(0)
  • 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` <to_replace> <replace_value>"
    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.

    0 讨论(0)
  • 2020-11-28 22:02

    Do it this way:

    find . -name '123*.txt' -type f -exec bash -c 'mv "$1" "${1/\/123_//}"' -- {} \;
    

    Advantages:

    • No pipes, no reads, no chance of breaking on malformed filenames.
    • Only one non-standard tool or feature: bash.
    0 讨论(0)
  • 2020-11-28 22:03

    In case you want to replace string in file name called foo to bar you can use this in linux ubuntu, change file type for your needs

    find -name "*foo*.filetype" -exec rename 's/foo/bar/' {} ";"
    
    0 讨论(0)
  • 2020-11-28 22:03

    Using rename from util-linux 2.28.2 I had to use a different syntaxt:

    find -name "*.txt" -exec rename -v "123_" ""  {} ";" 
    
    0 讨论(0)
  • 2020-11-28 22:03

    using the examples above, i used this to replace part of the file name... this was used to rename various data files in a directory, due to a vendor changing names.

    find . -name 'o3_cloudmed_*.*' -type f -exec bash -c 'mv "$1" "${1/cloudmed/revint}"' -- {} \;

    0 讨论(0)
提交回复
热议问题