How can I easily bulk rename files with Perl?

后端 未结 9 1099
一生所求
一生所求 2021-01-05 17:25

I have a lot of files I\'m trying to rename, I tried to make a regular expression to match them, but even that I got stuck on the files are named like:

<
相关标签:
9条回答
  • 2021-01-05 17:42

    I think mmv is your friend here.

    0 讨论(0)
  • 2021-01-05 17:44
    perl -e 'foreach $f (glob("File\\ Name*")) { $nf = $f; $nf =~ s/(\d+)$/sprintf("%03d",$1)/e; print `mv \"$f\" \"$nf\"`;}'
    

    A bit overkill maybe, but it does what is asked.

    0 讨论(0)
  • 2021-01-05 17:45

    if your remote has bash shell

    for i in File*; 
    do 
        case "${i##* }" in  [0-9][0-9] ) 
          echo  mv "$i" "${i% *} $(printf "%03d" ${i##* })" ;; 
        esac; 
    done
    

    remove "echo" to do actual renaming

    0 讨论(0)
  • 2021-01-05 17:46

    Is this a one-time thing? If so, I'm going to suggest something that might seem to be a cop out by many programmers here:

    Pipe the output of your command (find -type d | sort -r | grep ' [1-9][0-9]$') to a file and use an editor along with some global search/replace magic to create a script that does the renames.

    Then throw away the script.

    There's little fuss and little chance that you'll end up shooting yourself in the foot by having some attempt at a clever (but inadequately debugged) one-liner go off into the weeds on your files.

    0 讨论(0)
  • 2021-01-05 17:46

    In my debian it works well with rename, tested with 300 files.

     perl -e 'map `touch door$_.txt`, 1..300;'
     rename 's/(\d+)\.txt/sprintf("%03d.txt", $1)/e' *.txt
    
    0 讨论(0)
  • 2021-01-05 17:48
    find . -type d -print0 | xargs -0 rename 's/(\d+)/sprintf "%03d", $1/e' 
    

    or something like that, provided

    1. You have GNU find and GNU xargs (for -print0 and -0)
    2. You have the 'rename' utility that comes with perl
    3. There's only one group of digits in the filename. If there's more than one, then you need to do something with the regex to make it only match the number you want to reformat.
    0 讨论(0)
提交回复
热议问题