2

For example I have a file named 5.jpg. How can I rename it to aaaaa.jpg with char a 5 times.

I tried rename -v 's/(\d{1,})/a{$1}/g' * but this renames 5.jpg to a{5}.jpg, which is not what I want. I understand that second part of function isn't a regexp, this was just an attempt.

lcd047
  • 7,160
  • 1
  • 22
  • 33
Roman
  • 123
  • 3

2 Answers2

5

At least three different utilities imaginatively named rename(1) are floating around in the Linux waters: (1) the one that came with util-linux, (2) an older Perl script by Larry Wall further munged by Tom Christiansen, and (3) a newer Perl script evolved from the former and included with Unicode::Tussle. As far as I can tell, what you want can't be done with the util-linux version of rename(1). It can be done with either of the Perl scripts though:

rename -n 's/(\d+)/"a" x $1/e' 5.jpg

Output:

rename 5.jpg aaaaa.jpg

(drop the -n to actually rename the file).

lcd047
  • 7,160
  • 1
  • 22
  • 33
  • Hadn't realised there were (at least) three alternatives. I knew of two - a perl one and what I assume must be the util-linux version – roaima Jun 17 '15 at 14:51
  • Oh yeah, that's what I want! Thanks a lot, will search for more info – Roman Jun 17 '15 at 14:53
  • @roaima It came up in a previous SO thread: I posted an answer using the syntax of my `rename(1)` from `Unicode::Tussle`, and somebody complained some options were not recognized on his version. As it turned out he was using a different `rename(1)` (an older script munged by the Debian guys, I think). Amazingly, none of the authors thought that `rename` is actually a really common name and that it would be wise to call it something else instead. – lcd047 Jun 17 '15 at 14:57
2

If (and this is a big if) you are using the rename that uses a perl expression to modify filenames you can achieve what I think you want like this:

rename 's/(\d+)/"a" x $1/e' *

The e flag is explained in perldoc perlre. It modifies the interpretation of right hand side so that it is evaluated as a perl expresssion.

roaima
  • 107,089
  • 14
  • 139
  • 261