简体   繁体   中英

Linux Renaming files in a folder where the names is ab1.jpg, ab2.jpg, ab10.jpg etc

The order of the files is determined by a number that can be embedded in the filename, but sometimes in the beginning of the name eg file1.txt file2.txt file3.txt file10.txt file11.txt etc.. or 1.txt 2.txt 10.txt etc..

The renaming should result in names like... file01.txt file02.txt file03.txt file10.txt etc...

It is important that file1.txt will be file01.txt and not file10.txt to be file01.txt.

I think the filenames have to be formatted before renaming. I have no idea of how to do that on the command line, maybe it must be done by a script but I hope not.

The command should be given the number of digits we should have in the final name. If its possible to use a formatting string we also could give the position where we have the number(s).

Using the perl rename utility:

rename -n 's/\d+/sprintf("%02d", $&)/e' *.txt

Result would be:

$ ls
file10.txt  file1.txt  file2.txt  file3.txt

$ rename -n 's/\d+/sprintf("%02d", $&)/e' *.txt
rename(file1.txt, file01.txt)
rename(file2.txt, file02.txt)
rename(file3.txt, file03.txt)

If that looks good, remove the -n dry-run flag.

Note that the format string to sprintf determines the "width" of the zero-padding, so if you were dealing with filenames that get into the triple digits, you'd want to change that to "%03d" , etc..

$ ls
file100.txt  file10.txt  file1.txt  file2.txt  file3.txt

$ rename -n 's/\d+/sprintf("%03d", $&)/e' *.txt
rename(file10.txt, file010.txt)
rename(file1.txt, file001.txt)
rename(file2.txt, file002.txt)
rename(file3.txt, file003.txt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM