У меня есть несколько каталогов (папок, если хотите), которые следуют этой схеме

\20121022 Description of the directory's contents goes here\  

(у некоторых его нет, просто дата)

и мне нужно переименовать их, чтобы следовать следующей схеме

\2012-10-22 Description of the directory's contents ...\

Есть ли способ сделать это с помощью Windows cmd и инструментов, которые идут с ним (а именно, ren)? Если нет, то каков будет самый портативный способ сделать это? У меня очень ограниченный набор привилегий на машине, на которой я это делаю.

1 ответ1

4

Если вы начинаете с имени каталога в переменной, например, fdir:

set "fdir=20121022 Description of this directory"

Тогда ваш пакетный файл может разделить имя каталога:

set "fdiryear=%fdir:~0,4%"
set "fdirmonth=%fdir:~4,2%"
set "fdirday=%fdir:~6,2%"
set "fdirdesc=%fdir:~8%"

в этот момент переменные выглядят так:

fdir=20121022 Description of this directory
fdiryear=2012
fdirmonth=10
fdirday=22
fdirdesc= Description of this directory

Затем определите новое имя каталога и переименуйте каталог:

set "fnew=%fdiryear%-%fdirmonth%-%fdirday%%fdirdesc%"
ren "%fdir%" "%fnew%"

имя нового каталога будет:

fnew=2012-10-22 Description of this directory

Если вы можете дать мне больше информации о том, как вы хотите собрать список имен каталогов, я могу предоставить более полный сценарий.

Например, если все каталоги находятся в текущем каталоге, то пакетный файл будет выглядеть следующим образом:

@echo off

echo.
for /D %%f in ("2010*", "2011*", "2012*") do call :work "%%~f"
echo.
set "fdir="
set "fdiryear="
set "fdirmonth="
set "fdirday="
set "fdirdesc="
goto :EOF


:work
set fdir=%~1
set "fdiryear=%fdir:~0,4%"
set "fdirmonth=%fdir:~4,2%"
set "fdirday=%fdir:~6,2%"
set "fdirdesc=%fdir:~8%"

set "fnew=%fdiryear%-%fdirmonth%-%fdirday%%fdirdesc%"
echo Renaming folder "%fdir%" to "%fnew%"
rem    ren "%fdir%" "%fnew%"
goto :EOF

Пояснения:

Это отключит отображение команд по мере их выполнения, чтобы избежать большого количества помех на экране:

@echo off

Это отобразит пустую строку:

echo.

Команда для:

for /D %%f in ("2010*", "2011*", "2012*") do call :work "%%~f"

/D means to search for matches of Directory names only.
If you omit the /D, it will search for matches of Filenames only.

%%f (%%~f) is a variable name that gets set to the names of the matched directories.

[in ("2010*", "2011*", "2012*")] is a list of patterns to search for. 
In this case, it will only process directories that begin with a year: 
2010, or 2011, or 2012. You can edit this list for your needs. If you 
know that all directories in the current folder are in the same format 
and are candidates to be renamed, the list can be simply: ("*") like:  
for /D %%f in ("*") do call :work "%%~f"

the word "do" simply precedes the command that you want to "do" for each 
match found.

call :work says to execute the commands at the label :work for each match.

"%%~f" says to pass the matched directory name as the first argument to the 
commands at the label you specified (:work)  

The "~" in "%%~f" says to remove "quote" marks from %%f to avoid passing the 
directory name inside of 2 sets of "quote" marks. For example, if %%f contained 
"20121022 Description of this directory" then using "%%f" would pass 
""20121022 Description of this directory"", which would fail. "%%~f" will pass 
exactly 1 set of "quotes".

После обработки всех соответствующих имен каталогов выполнение возвращается к "эхо". команда, которая следует за командой "for ...".

Далее просто некоторая "очистка" для очистки переменных, используемых в скрипте, чтобы они не накапливались и не загромождали пространство переменных (окружение).

set "fdir="
set "fdiryear="
set "fdirmonth="
set "fdirday="
set "fdirdesc="

Следующий оператор выходит из пакетного сценария и завершает выполнение.

goto :EOF

Далее идет ярлык

:work

Labels begin with a colon at the first column followed by a 
label name made up of letters and numbers (no spaces). Labels are 
the targets of call and goto commands.  

Тогда команда:

set fdir=%~1

Sets the variable named "fdir" to be the directory name that was 
passed from the "for" command.

The "~" in %~1 means to use the name only without any surrounding "quote" marks.

Следующие команды:

set "fdiryear=%fdir:~0,4%"
set "fdirmonth=%fdir:~4,2%"
set "fdirday=%fdir:~6,2%"
set "fdirdesc=%fdir:~8%"
set "fnew=%fdiryear%-%fdirmonth%-%fdirday%%fdirdesc%"

Split up the directory name into the desired pieces, and 
define the "new" directory name.

Следующая команда:

echo Renaming folder "%fdir%" to "%fnew%"

Just displays the old and new directory names so you can see the 
progress on the screen.

И последние команды:

rem    ren "%fdir%" "%fnew%"
goto :EOF

Renames the directory and then "exits" to return from the call.

Примечание: я сделал реальную команду, чтобы переименовать каталог как комментарий, чтобы вы могли запустить пакетный файл и посмотреть, что произойдет, фактически ничего не переименовывая. После того, как вы запустите его и убедитесь, что правильные каталоги будут правильно переименованы, вы можете отредактировать строку, чтобы переименовать каталог, и снова запустить пакетный скрипт.

Для этого удалите "rem" из строки так:

rem    ren "%fdir%" "%fnew%"

Becomes:

ren "%fdir%" "%fnew%"

Всё ещё ищете ответ? Посмотрите другие вопросы с метками .