简体   繁体   中英

How to rename all files in a folder and create a renaming map

Note: I have access to both Linux and Windows platform so answers for any of these platforms are fine.

I have a folder which contains less than 10K .png files. I would like to:

1. rename all files as follows:

    <some_filename>.png to 0001.png
    <some_other_name>.png to 0002.png
    <another_name>.png to 0003.png
    and so on...

2. keep this name mapping in a file (see 1 for mapping)

In Windows: This should sort the list alphabetically and rename them all with numbers, padded to 4 characters.

It writes the bat file that does the renaming. You can examine it before renaming and running it, and doubles as a map of the filenames.

Filenames with ! characters will probably be an issue.

@echo off
setlocal enabledelayedexpansion
set c=0
for %%a in (*.png) do (
set /a c=c+1
set num=0000!c!
set num=!num:~-4!
>>renfile.bat.txt echo ren "%%a" "!num!%%~xa"
)

To rename all .png files in the current directory and to save the renaming map to renaming-map.txt file:

$ perl -E'while (<*.png>) { $new = sprintf q(%04d.png), ++$i; say qq($_ $new); 
    rename($_, $new) }' > renaming-map.txt

For example, given the following directory content:

$ ls
a.png  b.png  c.png  d.png  e.png  f.png  g.png  h.png  i.png  j.png

It produces:

$ perl -E'while (<*.png>) { $new = sprintf q(%04d.png), ++$i; say qq($_ $new); 
    rename($_, $new) }' 
a.png 0001.png
b.png 0002.png
c.png 0003.png
d.png 0004.png
e.png 0005.png
f.png 0006.png
g.png 0007.png
h.png 0008.png
i.png 0009.png
j.png 0010.png

Result:

$ ls
0001.png  0003.png  0005.png  0007.png  0009.png
0002.png  0004.png  0006.png  0008.png  0010.png

It should work both on Windows and Linux if perl is available (replace perl -E'...' with perl -E "..." on Windows (single -> double quotes)).

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