- Как переименовать все файлы в папке с помощью командной строки и более простыми методами
- Профессиональный подход
- Самый простой метод
- Редко используемый, но удобный способ
- Со сторонним софтом — удобнее
- Rename all files in a directory with a Windows batch script
- 2 Answers 2
- Explanation
- Переименование файлов и папок через командную строку Windows
- Rename file extensions in bulk from command line [CMD]
- Batch rename file extensions in bulk from CMD
- Recursively batch rename file extensions
- Remove file extensions in batch
- Add prefix to file names in batch
- Handling names with white spaces
Как переименовать все файлы в папке с помощью командной строки и более простыми методами
Порой вам необходимо сразу поменять имена множества файлов. Возиться с каждым по отдельности будет долго и комфортным этот метод не назовешь. Существуют три простых способа эффективного изменения названий группы файлов и у каждого из них есть свои преимущества. Отмечу, что во всех случаях команды необходимо вводить без кавычек.
Профессиональный подход
Чтобы зайти в командную строку, в каталоге с файлами, которым вам предстоит дать другие имена, введите « cmd ». Ввод подтвердите Энтером. Результатом действия станет открытие командной строки для данной директории.
В качестве примера поменяем расширение всех JPG-картинок. Чтобы сделать это, введите команду в формате « ren *.jpg *.png ». Для завершения действия нажмите Энтер. В итоге у всех картинок, расширение которых изначально было JPG, оно поменяется на PNG.
Самый простой метод
В стандартном системном проводнике очень просто переименовать одиночный файл. В его контекстном меню выбирается соответствующий пункт и вводится новое имя. Существуют и другие способы. Но если у вас сотня файлов, которым нужно подобрать стандартные новые названия, то задача тоже решаема стандартными средства Виндоуз.
Сначала создайте новый каталог и переместите туда все файлы, которым вы хотите дать новые имена. Выберите табличное отображение файлов. Затем вам необходимо выделить файлы. Нажмите Shift и не отпуская его жмите стрелку вниз. Второй подход еще проще — используйте клавиатурную комбинацию Ctrl и A для выделения всех файлов в директории.
После этого в контекстном меню первого из выделенных вами ранее файлов выберите опцию переименования и введите название, которое станет использоваться в дальнейшем. Подтвердите произведенное действие Энтером. Успешным результатом переименования станет присвоение всем файлам в каталоге имен, которые состоят из общей части, например «Изображение» и номера в списке — «единица», «двойка», «тройка» и так далее.
Редко используемый, но удобный способ
Проще всего будет сначала войти в нужный вам каталог и лишь оттуда запустить PowerShell щелчком по соответствующему пункту в меню « Файл ».
Допустим у вас есть целый ряд картинок, в именах которых содержится слово «Изображение» и вы хотите, чтобы из названия было понятно, что они относятся к июню текущего года.
В этом случае команда будет иметь следующий вид: « dir | rename-item -NewName ». После ввода примените ее нажатием Энтера. Разумеется, это только один из возможных примеров. У вас может быть другая исходная общая составляющая названий файлов и другая итоговая.
Со сторонним софтом — удобнее
Мощнейший инструмент для работы с файлами Total Commander уже не первое десятилетие пользуется огромной популярностью. Если у вас он уже установлен, то задача по групповому переименованию картинок или текстов станет решаться намного проще, чем инструментами, которые предусмотрены в самой системе.
После входа в программу переместите все файлы, с которыми вам предстоит работать, в один каталог. При необходимости его нужно будет создать. Все файлы легко выделяются одновременным нажатием Ctrl и A .
Чтобы перейти к нужной вам опции используйте сочетание клавиш M и Ctrl или найдите ее в меню «Файл». Вам будет предложено определить маску.
В этой строке вы печатаете название, которое станет использоваться в будущем. Сразу же вам видно, как станет выглядеть итог вашей работы. Предусмотрены опции изменения расширения, а также использования в именах текущей даты. Опция «счетчик» дает возможность добавить к названиям файлов порядковые номера. Применить изменения можно щелчком по экранной кнопке «Выполнить».
Какие файловые менеджеры и другие инструменты работы с файлами нравятся вам больше всего?
Rename all files in a directory with a Windows batch script
How would I write a batch or cmd file that will rename all files in a directory? I am using Windows.
2 Answers 2
A FOR statement to loop through the names (type FOR /? for help), and string search and replace (type SET /? for help).
UPDATE — 2012-11-07
I’ve investigated how the RENAME command deals with wildcards: How does the Windows RENAME command interpret wildcards?
It turns out that this particular problem can be very easily solved using the RENAME command without any need for a batch script.
The number of characters after the _ does not matter. The rename would still work properly if 120×90 became x or xxxxxxxxxx . The important aspect of this problem is that the entire text between the last _ and the . is replaced.
As of Windows 7 you can do this in one line of PowerShell.
Explanation
powershell -C «. » launches a PowerShell session to run the quoted command. It returns to the outer shell when the command completes. -C is short for -Command .
gci returns all the files in the current directory. It is an alias for Get-ChildItem .
| % <. >makes a pipeline to process each file. % is an alias for Foreach-Object .
$_.Name is the name of the current file in the pipeline.
($_.Name -replace ‘120×90′, ’67×100’) uses the -replace operator to create the new file name. Each occurrence of the first substring is replaced with the second substring.
rni changes the name of each file. The first parameter (called -Path ) identifies the file. The second parameter (called -NewName ) specifies the new name. rni is an alias for Rename-Item.
Переименование файлов и папок через командную строку Windows
Хотя командная строка в Windows это далеко не такой же мощный инструмент по сравнению с терминалом в Linux, она обладает множеством базовых функций. Сегодня поговорим о переименовании файлов и каталогов.
За переименование файлов и папок в командной строке Windows отвечает команда RENAME. Можно использовать и укороченный вариант REN. Поскольку использовать укороченный вариант явно проще, в дальнейшем в этой статье будем использовать его.
Синтаксис команды ren очень прост для понимания:
REN [путь_к_файлу]\[текущее_имя_файла] [новое_имя_файла]
Если речь идёт о текущем каталоге, то достаточно команды
Эта команда переименует файл primer.txt в new_primer.txt.
Если речь идёт не о текущем каталоге, то требуется указать полный путь к файлу:
При указании нового имени нельзя задать другой каталог. Команда ren только даёт новое имя файлу, не перемещая его.
Аналогично можно переименовать и папку:
Обратите внимание, что наличие пробела заставляет нас использовать кавычки.
Команда ren допускает и работу с несколькими файлами. Но тут нужно сделать весомую оговорку — ren работает с файлами и папками, у которых одно местоположение. Что это значит на практике? Задать одно и то же имя нескольким файлам одновременно команда ren не позволит. Ведь местоположение этих файлов совпадает. В этом случае будет выведена ошибка «файл с таким именем уже существует или не найден». Причем первый по имени файл всё таки будет переименован.
А вот массово изменить расширение файлов команда ren способна. Для этого можно ввести команду вида
Это изменит всем файлам в текущем каталоге расширение с txt на doc.
Вот, пожалуй, и всё, что нужно знать о команде rename . Никаких параметров у этой команды нет.
Rename file extensions in bulk from command line [CMD]
This post talks about how to batch rename file extensions from command line. No 3rd party tools are required. At the end of the post, you can find a download link for the batch file script.
Batch rename file extensions in bulk from CMD
We can change the extension of files in batch using rename command. For example, let’s say you have set of files with extension .log and you want to rename them to .txt. You can do this with the below command
The drawback with this command is, we can’t use it to rename file extensions recursively in the sub folders. Next, we’ll look at a solution which allows us to do so.
Recursively batch rename file extensions
If you want to rename files from one extension to another, recursively in all sub folders, then you can use the below command.
For example, if you want to rename all xml files to txt files, the command would be as below
Remove file extensions in batch
The below command would remove extension for the specified file types.
If you want a batch file script, it can be downloaded from the below link:
Batch file script for renaming file extensions in bulk
Add prefix to file names in batch
If you want to add any prefix to file names, it can be done as in the below example. Here we try to add ‘photo’ to every jpg file in the current folder and subfolders.
Similarly, we can add a number to a file name.
Handling names with white spaces
If the new name you want to assign to the files has white space within it, it can be done by adding double quotes around the file name. So that forfiles does not misinterpret this doublequotes, you need to escape them with ‘\’
For example to add ” – pic.jpg” to each of the jpg files, the command would be as below.
I want only the extensions of files starting with certain type of names to be renamed, within the folder as well as subfolders.
How can I do it?
For example:
rename all files starting with the name “*-common.xml” to “*-common.xml.txt”
The other .xml files have to be left intact.
Figured it by out myself.
forfiles /S /M *-common.xml /C “cmd ren *-common.xml *-common.xml.txt”
If you are using forfiles, you donot need to use * again in the cmd part.
Thanks for these hints 🙂 Is it also possible to include a space in the prefix? I tried the following:
=> The syntax of the command is incorrect
=> ERROR: Invalid argument/option…
The file name need to be surrounded with double quotes if it has white spaces. Added example command to the post.
I have here some files with ending like this
(1).txt
e.g. file_a(1).txt
I tried this
forfiles /S /M *.ext1 /C «cmd /c rename @file @fname.ext2» for renaming them to .txt
e.g. file_a.txt
Can you help me?
The “Add prefix to file names” code is faulty. When I ran it, it keeps adding the prefix to all of the files in the folder over and over again until I kill it.
It worked fine for me. Can you tell me how many files you have in the folder that you were intending to add the prefix?
Same issue here. I believe it happens when there are special characters in the file name (i have brakets “[]” and commas “,”.
I just tried to rename midi karaoke files to midi files,
This doesn’t work if the file name has spaces in it, (OS Win XP Sp3).
But I found other solution that works flawlessly
Thanx a million times man! you saved me
None of the websites including this has alluded to the renaming of files by removal a second extension.
If a folder contains several files like *.mo.po and *.mo as file extensions, how do we selectively rename the *.mo.po to *.po whilst not touching the *.mo that were already there?
Try this command
It works only if you don’t have files with the same name and two different extensions.
ex: 1.mo.po and 1.mo. You would get error in renaming as a file already exists with the name.
Let us know if it works for your usecase.
A virus added .zwrkocj to all file types, how would I remove that?
If it has converted files like file.ext to file.ext.zwrkocj then I think you can run the below to get back to original state.
How to append the name of the parent folder onto the prefix of the file name?
forfiles /S /M *.ext /C “cmd /c rename @file @fname”
changed files in all of C drive, right?
how can you specify a specific folder and its subfolders?
how can you turn off recursion?
We can’t restrict the recursion to one level. You might need to write a custom batch script to do that.
You have to run the command in the folder you wish to treat as the root. If you run the command from C:\, then yes, it will rename all files matching the filename criteria you specify.
I have one question.
I created a bat file for renaming all the files to one extension
but this also changes the extension of my bat file.
Can I exclude bat file in any way.
Thanks for your help on this.
Why not place this bat file in some other folder, outside the current directory tree?
Great stuff guys. This probably saved me about an hours worth of work.
I can’t seem to get the white spaces code to work.
forfiles /s /m *.* /C “cmd /c rename @file \”(PA) @file\””
Is there anything that is wrong with the above code. This is the following error “Unrecognized token in source text.”
It worked for me.
I guess something could be wrong if you had copy pasted the command. Especially the double quotes usually get wrong. I would suggest to type the command(rather than copy/paste), it should work.
Would the error be caused by running the commands simply from a PS1 Script? That’s the only reason I can think of.
Well I ended up Scripting a simply tool in Access VBA.
‘forfiles’ command seems to have come very close to serving my need but is there a way to remove a prefix from a set of files recursively?
Example:
TT-*.* to *.*
I want to remove ‘TT-‘ from all the files
Any idea’s on how to rename hidden files?
When I run the command it can’t find the files because they have the hidden attribute.
I don’t see a /H or similar switch in the command help.
Any help would be appreciated.
Thank you.
You can remove the hidden attribute first with ‘attrib -h’ and then rename the file.
i want to add one set of numbers to file names and have multiple folders containing few files in every forlder
like folder 1003 has 3 files with names like : 1003_blue_M , 1003_Black_M, 1003_Red_S, etc… now i want to change the file name to 1003_blue_M_12345, 1003_Black_M_12345, like wise…. every folder will have new number to be added..kindly suggest how i can replace the entire bulk of files ->in folders
Thanks
Niyaz
I do not understand the example for changing file extension of particular file and where to apply this command. pl. clarify
as Will said:
“The “Add prefix to file names” code is faulty. When I ran it, it keeps adding the prefix to all of the files in the folder over and over again until I kill it.”
It keeps adding the prefix till you kill it.
is there a stop or pause code ?
I am not able to replicate this. It is stopping after renaming all the files.
May be you guys have a different setup in your cases.
How to remove double quotation using forfiles to save as text file. Please see below my code.
the result was this : “FO_FullDBBackup_201509211126”, 9/21/2015, 11:26:50 AM, 20001
i want to look like this : FO_FullDBBackup_201509211126, 9/21/2015, 11:26:50 AM, 20001
hi, I wanted to know how to rename files so that if it detects the same name it will change the name to add a number to it for example:
ren *.* *.jpg
so if it has 1.thm 1.thumb it will rename the first file 1.thm and then when it tries to rename 1.thumb to jpg it says that its duplicate. so I need it to rename something like 1-1.jpg or 1a.jpg, 1b.jpg, etc.
thanks in advance.
Hi I tried to append the prefix XTO_12345678W500_ to about 200 pictures
the command will repeat the addition (XTO_12345678W500_) until the file name is 256 almost characters! Then crashes.
I tried to add only 12345678W500_ and it works fine.
To this tried to add the remaining XTO_ and it did it again: fill the name to about 256 (did not count!) characters. and then crashes!
I want to change an extension from .exe to .pdf or .jpg without changing the proprietes of .exe
Can somebody help me with this?
forfiles /s /M *.txt /C “cmd /c rename @file [email protected]”
when i am using the above command for more then 40 files in the folder it gives an error with the repetition of filename with .ext ?
any solution guys with some minor changes in the above code so i can rename the 100s of filename without repeating it.
I want to remove prefixes from file names. I have successfully used the following to rename files in a directory, but it does not work for subdirectories
rename “01 – *.mp3” “/////*.mp3”
I tried
forfiles /S /M 0*.mp3 /C “cmd /c rename @file \”//@fname.mp3\””
however it gives me an error that
ERROR: Files of type “0*.mp3” not found.
however dir 0*.mp3 /s works fine, so there are files matching the criteria
Variations to enclose the search in “” also give the same error. I tried
forfiles /S /M “0*.mp3” /C “cmd /c rename @file \”//@fname.mp3\””
I have a script that renames files and adds a time stamp for the current time. the script works great however it will only execute on one file in a folder each time it runs. I need it to run on all file in a folder each time. What am i Missing?
@echo off
for %%f in (*.*) do echo %%f
for /f “delims=” %%a in (‘wmic OS Get localdatetime ^| find “.”‘) do set dt=%%a
set YYYY=%dt:
12,2%
set stamp=D%YYYY%%MM%%DD%T%HH%%Min%%Sec%
Hi,
I want to use the rename command for changing the extension of files in a folder to “*.gz.par”.
For eg the files in the folder are:
abc.par
xyz.gz.par
I need to rename the abc.par to abc.gz.par and xyz.gz.par should stay the same.
Now when I run the command: rename *.par *.gz.par
it changes the abc.par correctly to abc.gz.par
but it also changes xyz.gz.par to xyz.gz.gz.par
Please help…
Hi,
every morning at work i start my day by serching a file received the night before on folder1 and having name like RetxxxxxxxDDYY (the DDYY is the date of the last working day when the file has been created).
Is there a way to copy the last file received from the folder1 to folder2 using a script knowing that the files created avery day still on this folder.
Many thanx in advence
How do I change files’ type in D drive?
Kryptik virus or trojan changed the file names from original file names to include .crypted – I used the remove file extensions in batch command copied the original line into notepad modified it to be
forfiles /S /M *.crypted /C “cmd /c rename @file @fname”
then pasted it from notepad into the cmd window
And voila all the files that had been changed got changed back to the original filenames. Thank you for this resource.
Thank you thank you.
A virus added .crypted to all file types, how would I remove that? like .doc.crypted , .ppt.crypted, jprg.cypted
i have done ren*.* *. but i was for one directory, i want forfolder and sub folder or hole directory in one batch file
Thank you Masim!
Your command line really works, helped me remove all “.cryped”
I have a list of files in a single directory and want to bulk change the names of all the files so that the files retain their original filename + unique datetimestamp for example all of the current files have a yymmdd.cfx name and 2 have a yymmdd.cfx_2 extension I need to change all of these or at least the .cfx files to have current file name + yyyymmddhhmmss getting current timestamp that’s unique.. I can’t get your example to work and it’s driving me crazy.. thanks
I have a client that received an email from “FedEx” about a delay in shipment. We had just ordered memory the day before so they opened it. It popped up a ransomware msg and encrypted several .docx files and changed their extensions to .docx.crypted. I opened one of the files and it is encrypted. They have TrendMicro loaded and it totally ignored the problem. I scanned with Windows Security Essentials and it found “Ransom:HTML/tescrypt.D”. Only two PC’s received this email and encrypted files. Subsequent scans on server and 11 other PC’s found no problems. Will try some of the “unencrypting” ideas above. Luckily, their aren’t two many files. Appears to be only on files on desktop. Thanks for all the ideas and beware of the FedEx emails.
I want remove to 6 random chrachter extension.
Forexample
We have 2 f’iles
as
1.jpg and 1.jpg.hgkbgt
I want to delete secondary file at the same folder.
1.jpg file will be stay in same folder
How I could that
Some how The dot between the body and the extension of all the songs has been removed. Is there a way to put the dot back other than one at a time? This happen to one complete music folder.
Below is an example
Judith Durham, Danny Boymp3 (NOTE NO PERIOD AFTER BOY)
I want to rename files in sub-folders as name which is in that sub-folder name via batch file. Can u help me?
Thankyou very much, this worked for me!
I want change the extension of files in subfolders.most important is I don’t know the file name and folder name.both are dynamic..How should I do?? Can you help me?
Thanks in advance.
I need to batch or mass rename 76k+ file names in multiple folders and subfolders in a directory. I need the new name to be a specific unique name.
I cannot use a third party application; I can only use command prompt or powershell or whatever comes with Windows 2010. I also can use the standard version of the app Beyond Compare.
For example, I need to change:
C:\Users\joe\Desktop\Parentfolder\child folder\grandchildfolder##NA##1329001.00##1329001.00\company xyz.pdf
Parent folder is the lowest common folder in the shared hierarchy of all files i need to change
I have the full path containing the old name in an excel column matched to the full path containing the new name in the adjacent excel column. The new name in cell AB must be the name that replaces the old name in cell A2. There is not a pattern to the names and they do contain spaces and non alpha-numeric characters.
I have tried using “ren” by and adding ren “old path with old name” “new path with old name” but cannot get it to work. The closest I have come is renaming files in folders from command prompt at the lowest folder location & can only rename the files in that folder only
I did this by pasting the ren command with the old and new name from spreadsheet to wordpad & then saving it as a .bat
I badly needed this to rename my iPhone’s video extensions to play in Adobe Premiere pro.
Thanks a lot.
forfiles /S /M *.jpg /C “cmd /c rename @file [email protected]”
this command infinatly rename image name, i mean it infinatly add photo prifix, i want to add photo prifix only once
Thank you. It worked like a charm.
I wrote the following to rename all files to .mp4
How do I get the script to all run on all sub-folders?
Thank you!
@echo off
ren * *.mp4
Hi how do you rename folders in other drives/folders?