Sunday, May 19, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 498  / 1 Year ago, sat, february 25, 2023, 11:04:04

How can I batch rename, using the terminal, a set of files where multiple numbers share the same prefix so that all those prefixes are set to new ones?


For example:


011.foo.txt   -> 001.foo.txt
011.bar.psd -> 001.bar.psd
011.baz.gif -> 001.baz.gif
012.qux.js -> 002.qux.js
012.corge.png -> 002.corge.png
...
020.thud.txt -> 010.thud.txt

I'd like to use the rename command if possible:


rename [ -h|-m|-V ] [ -v ] [ -0 ] [ -n ] [ -f ] [ -d ] [ -e|-E perlexpr]*|perlexpr [ files ]

Really appreciate your help figuring this out, Thanks!


More From » command-line

 Answers
4

Using the perl rename as requested.


For what your question demonstrates:


rename -n 's/^(d+)/sprintf "%03d", $1-10/e' *

dry-run output:


rename(011.bar.psd, 001.bar.psd)
rename(011.baz.gif, 001.baz.gif)
rename(011.foo.txt, 001.foo.txt)
rename(012.corge.png, 002.corge.png)
rename(012.qux.js, 002.qux.js)
rename(020.thud.txt, 010.thud.txt)

For what the question title says, with actual sequential prefixes:


rename -n -E 'use vars q{$n}' -e 's/^(d+)/sprintf "%03d", ++$n/e' *

rename(011.bar.psd, 001.bar.psd)
rename(011.baz.gif, 002.baz.gif)
rename(011.foo.txt, 003.foo.txt)
rename(012.corge.png, 004.corge.png)
rename(012.qux.js, 005.qux.js)
rename(020.thud.txt, 006.thud.txt)



For the first one, if you don't want to hardcode the delta 10:


rename -n -E 'use vars q{$delta}' -e '
s{^(d+)}{
$delta = $1 - 1 unless defined $delta;
sprintf "%03d", $1 - $delta
}e
' *

[#1443] Monday, February 27, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
antoccasiona

Total Points: 430
Total Questions: 127
Total Answers: 131

Location: Netherlands
Member since Sat, Jun 26, 2021
3 Years ago
antoccasiona questions
Sat, Oct 23, 21, 22:34, 3 Years ago
Sat, Sep 24, 22, 09:39, 2 Years ago
Sun, Jan 15, 23, 11:08, 1 Year ago
;