4

Possible Duplicate:
Renaming lots of files in Linux according to a pattern

I have multiple files in this format:

file_1.pdf
file_2.pdf
...
file_100.pdf

My question is how can I rename all files, that look like this:

file_001.pdf
file_002.pdf
...
file_100.pdf

I know you can rename multiple files with 'rename', but I don't know how to do this in this case.

Community
  • 1
  • 1

2 Answers2

13

You can do this using the Perl tool rename from the shell prompt. (There are other tools with the same name which may or may not be able to do this, so be careful.)

rename 's/(\d+)/sprintf("%03d", $1)/e' *.pdf

If you want to do a dry run to make sure you don't clobber any files, add the -n switch to the command.

note

If you run the following command (linux)

$ file $(readlink -f $(type -p rename))

and you have a result like

.../rename: Perl script, ASCII text executable

then this seems to be the right tool =)

This seems to be the default rename command on Ubuntu.

To make it the default on Debian and derivative like Ubuntu :

sudo update-alternatives --set rename /path/to/rename

Explanations

  • s/// is the base substitution expression : s/to_replace/replaced/, check perldoc perlre
  • (\d+) capture with () at least one integer : \d or more : + in $1
  • sprintf("%03d", $1) sprintf is like printf, but not used to print but to format a string with the same syntax. %03d is for zero padding, and $1 is the captured string. Check perldoc -f sprintf
  • the later perl's function is permited because of the e modifier at the end of the expression
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • This does not seem to make any sense. How is this connected to Perl? Standard Linux `rename` does not have `-n` and does not support advanced replacement sed-style. Perl `rename` is very simple and cannot do this by default either. What is this? Please give more thorough example. – mvp Jan 14 '13 at 22:35
  • [`rename`](http://search.cpan.org/perldoc?rename) on CPAN does have `-n`. – ikegami Jan 14 '13 at 22:39
  • If you have a `ELF` binary instead of `Perl`, this is another tool, nothing to do with the explained one. – Gilles Quénot Jan 04 '17 at 15:33
  • I have no experience in Perl, but [I know regular expressions](https://xkcd.com/208/). Would you mind updating this to briefly explain its usage more broadly? I was personally able to remove the `.txt` file extension from some files with `rename s/(.*).txt/sprintf($1)/e' *.txt` but I do not fully understand how it worked. What is the `s` at the beginning and the `/e` at the end, and why is the print statement immediately after the regular expression? – Keavon Mar 21 '17 at 06:16
  • Added explanations – Gilles Quénot Mar 22 '17 at 22:45
1

If you want to do it with pure bash:

for f in file_*.pdf; do x="${f##*_}"; echo mv "$f" "${f%_*}$(printf '_%03d.pdf' "${x%.pdf}")"; done

(note the debugging echo)

Gilbert
  • 3,740
  • 17
  • 19