batch search and replace folders names

断了今生、忘了曾经 提交于 2020-01-06 08:17:08

问题


i'm using batch file (named as folder.bat) to add the string "_v0_1" for each foler name under "my folder" (i have about 100 folders under "my folder")

I'm calling my batch (folder.bat) from a onother batch file that contains this rows(for example):

call folder arbiter_logic

call folder arbiter_logic_old

the problem, is that the batch rename folders also when the folder name is longer than the variable name (%1) and i want to avoid it .

I want that the renaming action will execute only if there is exact match between variable %1 and the folder name. Here's my code:

setlocal enabledelayedexpansion
pushd G:\my folder
for /f "tokens=* delims= " %%a in ('dir /b/ad') do (
set x=%%a
set y=!x:%1=%1_v0_1!
ren !x! !y!
)
::==
cd..

currently the unwanted result is:

arbiter_logic_v0_1

arbiter_logic_v0_1_old_v0_1

and the wanted result is that the batch will change the folders name as shown below:

arbiter_logic_v0_1

arbiter_logic_old_v0_1

I'm assuming that there is a need to apply search and replace method within folders names, but i'm not sure how to do so.

vb script will also be a suitable solution if batch file won't do.

Thanks in advance. shay.


回答1:


There is no need for your "folder.bat". You can simply rename the directories within your main script.

ren "g:\my folder\arbiter_logic" "arbiter_logic_v0_1"
ren "g:\my folder\arbiter_logic_old" "arbiter_logic_old_v0_1"

You can save some typing by using a FOR loop, especially if you have many renames to do

for %%F in (
  "arbiter_logic"
  "arbiter_logic_old"
) do ren "g:\my folder\%%~F" "%%~F_v0_1"

If you really want to call folder.bat within your main script, then your "folder.bat" can be as simple as.

@ren "g:\my folder\%~1" "%~1_v0_1"


来源:https://stackoverflow.com/questions/13699785/batch-search-and-replace-folders-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!