Rename multiple files from command line [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-06 01:40:53

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

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!