Rename multiple files from the command line

Possible duplicate:
Renaming a large number of files in Linux according to the pattern

I have several 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 that you can rename multiple files using β€œrename”, but I don’t know how to do this in this case.

+3
bash perl rename file-rename
source share
2 answers

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

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

If you want to make a dry run to make sure that you are not killing any files, add the -n command 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 .

Make Debian default and derived like Ubuntu :

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

Explanation

  • s/// is a basic substitution expression: s/to_replace/replaced/ , check perldoc perlre
  • (\d+) grab with () at least one integer: \d or more: + in $1
  • sprintf("%03d", $1) sprintf as printf , but not used for printing, but for formatting a string with the same syntax. %03d is the zero fill, and $1 is the captured line. Check perldoc -f sprintf
  • a later perl function is allowed due to the e modifier at the end of the expression
+13
source share

If you want to do this with pure bash:

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

(pay attention to echo debugging)

+2
source share

All Articles