Как изменить символ, встроенный в имена файлов, на другой символ?

1217
PilotMom

В каталоге с несколькими подкаталогами мне нужно изменить имена файлов, которые имеют этот _символ, на другой символ:, .например:

ABC12345_DEF --> ABC12345.DEF 

Мне нужно сделать это рекурсивно через дерево каталогов.
Последние три символа имени файла не всегда совпадают.

Использование подстановочных знаков переименования по обе стороны _или .не работает (плюс мне нужно сделать это через несколько каталогов).

0
Операционная система? Daniel Beck 13 лет назад 2
возможный дубликат http://superuser.com/questions/205083/command-line-recursive-rename-move-in-windows Patrick 13 лет назад 0
Windows XP. Последние три символа не совпадают в файлах PilotMom 13 лет назад 0

3 ответа на вопрос

1
Kevin Fegan

This batch file should do it for you.

Copy the batch file below into a text file and save it as xrename.cmd (or "whatever you want.cmd").

If you just run the file like this:
xrename.cmd

It will look in the current folder and all subfolders, and rename all files like: ABC12345_DEF to ABC12345.DEF (anything like "text_moretext" to "text.moretext").

You can also provide values for "search-string", "replace-string", and "search-pattern" on the command line.

To show instructions, run it like this:
xrename.cmd /help

Note: I made the batch file to only display the files that will be renamed, no renaming will actually take place. You can run the batch file and see what will happen without actually renaming anything. Once you have run it and are confident the correct files will be properly renamed, you can delete the line as described below to make renaming active, then run the batch file again.

You might have to modify the value of "search-pattern" to display the files you want.

At the labels ":default1" and ":default2", you can edit the values for "match-string" "search-pattern" and "replace-string" to suit your needs.

This batch file has some error checking and it won't fail if the "match-string" is found in the names of any of the folders or subfolders.

@echo off if "%~1%~2%~3."=="." goto :default1 if /i "%~1."=="/help." goto :syntax if "%~1."=="." goto :syntax rem %2 can be empty to use "*matchstring*" as the "search-pattern" rem %3 can be empty to make replacement with empty string (delete matchstring). set "matchstring=%~1" set "replacestring=%~3" if "%~2."=="." goto :default2 set "searchpattern=%~2" goto :start :default1 set "matchstring=_" set "replacestring=." :default2 set "searchpattern=*%matchstring%*" :start set "renamecount=0" set "errorcount=0" echo. for /r %%f in ("%searchpattern%") do call :work "%%~dpf" "%%~nxf" echo. if %renamecount% EQU 0 echo No files renamed. if %renamecount% EQU 1 echo Renamed %renamecount% file. if %renamecount% GEQ 2 echo Renamed %renamecount% files. if %errorcount% EQU 1 echo %errorcount% error renaming files. if %errorcount% GEQ 2 echo %errorcount% errors renaming files. echo. goto :cleanexit :work set matchedfilepath=%~1 set matchedfilename=%~2 rem You can't do it directly like this: rem set "newfilename=%matchedfilename:%matchstring%=%replacestring%%" for /F "usebackq delims=" %%g in (`echo set "newfilename=%%matchedfilename:%matchstring%=%replacestring%%%"`) do %%g echo In path "%matchedfilepath%": Renaming "%matchedfilename%" to "%newfilename%" rem delete the next line (goto :EOF) to make renaming active goto :EOF ren "%matchedfilepath%%matchedfilename%" "%newfilename%" if %errorlevel% NEQ 0 goto :workerror if not exist "%matchedfilepath%%newfilename%" goto :workerror goto :workok :workerror echo Rename "%matchedfilepath%%matchedfilename%" failed. set /A errorcount=errorcount+1 echo. goto :EOF :workok set /A renamecount=renamecount+1 goto :EOF :syntax rem:syntax echo. echo Syntax: echo %~nx0 ["match-string" ["search-pattern"] ["replace-string"]] echo. echo Search for files matching "search-pattern" in current folder and through all echo subfolders. For each matched file, rename file by replacing "match-string" echo with "replace-string". echo. echo If "replace-string" is empty or not specified, rename file by deleting echo "match-string". echo. echo If "search-pattern" is empty, use "*matchstring*" as the "search-pattern". echo. echo If "match-string" "search-pattern" and "replace-string" are all empty or not echo specified, then defined defaults will be used. echo. echo If "search-pattern" and/or "replace-string" are NOT empty then "match-string" echo cannot be empty, echo. goto :EOF :cleanexit set "matchstring=" set "replacestring=" set "searchpattern=" set "renamecount=" set "errorcount=" set "matchedfilepath=" set "matchedfilename=" set "newfilename=" goto :EOF 

Once you have run the batch file and are confident the correct files will be properly renamed, you can edit the file to remove the line(s) described to make renaming active, then run the batch file again.

To do that, find the two lines that are like this:

rem delete the next line (goto :EOF) to make renaming active goto :EOF 

Then, remove the line that says "goto :EOF" (or remove both lines).

Don't remove "goto :EOF" from any other place in the batch file (it can be found in a few places so be sure to remove the correct one).

If this isn't working for you, or if you want me to explain anything in the batch file, just let me know.

0
Patrick

модифицируя то, что я нашел в этом пакетном сценарии переименования / перемещения, это должно работать:

for /r %x in (*_*) do ren "%x" *.* 
он выводит полный путь в кавычках, за которыми следует *. *, но имена в каталогах не изменяются PilotMom 13 лет назад 0
0
Asterisk

Следующее должно работать. Я использовал moveвместо того, чтобы из- renза особенностей renобработки имен файлов в кавычках.

for /f "tokens=1,2 delims=_" %i in ( 'dir /s/b *_*.' ) do @( move "%i_%j" "%i.%j" ) 

Вы можете удалить, @если вы хотите визуально отслеживать ход выполнения команды.

Ты замечательный !!! БЛАГОДАРЮ ВАС!!!! PilotMom 13 лет назад 0
Могу ли я поместить это, как написано в файле BAT для будущего использования? или мне нужно что-то добавить, чтобы это заработало ... Я очень ценю вашу помощь! PilotMom 13 лет назад 0
Чтобы он работал в пакетном файле, вам нужно изменить все переменные, которые используют один знак процента, на двойной знак процента; т.е. измените все экземпляры `% i` на` %% i` и `% j` на` %% j`. Asterisk 13 лет назад 0
Поскольку `dir / s / b` возвращает полный ** путь ** и имя файла,` ren` потерпит неудачу, поскольку `ren` не нравится, когда второй аргумент`% i.% J` содержит путь. Move нравится это просто отлично. Kevin Fegan 11 лет назад 0
Поскольку разделитель равен "_ _" (`delims = _`), а" dir / s / b` "возвращает полный путь и имя файла, это решение не будет выполнено, если какая-либо часть пути содержит один или несколько из" `_`" (подчеркивание). Это решение также потерпит неудачу, если имя файла содержит более одного из «` _` », поскольку полное имя файла не будет представлено`% i` и `% j`. Kevin Fegan 11 лет назад 0

Похожие вопросы