从一个列表中搜索文件名,然后在BATCH中将其替换为另一个列表

时间:2018-09-10 14:27:31

标签: batch-file rename batch-rename

我有两个文件:

old_names.txt
  oldname1
  oldname2 

new_names.txt 
  newname1
  newname2 

我想在我的文件夹中搜索包含 “ old_names”的文件名,并将“ old_name”字符串替换为相应的“ new_name”。

for /f %%i in (old_names.txt) do (

 // get corresponding %%j new_name

 for /f %%a in ('dir /b /a-d *%%i*') do ren %%a %%j

)

如何检索对应的new_name?

2 个答案:

答案 0 :(得分:2)

对于文件对概念,如果我理解正确,基本上需要逐行同时读取两个文件,这可以像this answer中所示完成。所以这是一个可能的代码:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=D:\path\to\root_dir" & rem // (directory containing files to rename)
set "_FILE1=D:\path\to\old_names.txt"
set "_FILE2=D:\path\to\new_names.txt"

rem // Count number of lines of 1st file (2nd file is not checked):
for /F %%C in ('^< "%_FILE1%" find /C /V ""') do set "NUM1=%%C"

setlocal EnableDelayedExpansion
rem // Change into root directory:
cd /D "%_ROOT%" || exit /B 1
rem // Here input redirection is used to read both files simultaneously:
9< "!_FILE1!" 8< "!_FILE2!" (
     rem // Loop through the number of lines of the 1st file:
     for /L %%I in (1,1,%NUM1%) do (
         rem // Read a line from the 1st file:
         <&9 (set "LINE1=" & set /P "LINE1=")
         rem // Read a line from the 2nd file:
         <&8 (set "LINE2=" & set /P "LINE2=")
         rem /* Assign line strings to `for` variables to later avoid nested
         rem    delayedly expanded environment variables: */
         for /F "tokens=1,2 delims=| eol=|" %%I in ("!LINE1!|!LINE2!") do (
             rem // Get list of files matching the partial name:
             for /F "delims= eol=|" %%F in ('dir /B /A:-D "*!LINE1!*"') do (
                 endlocal
                 rem // Store current file name:
                 set "NAME=%%F"
                 setlocal EnableDelayedExpansion
                 rem // Do the actual sub-string replacement and rename file:
                 ECHO ren "!NAME!" "!NAME:%%I=%%J!"
             )
         )
     )
)
endlocal

endlocal
exit /B

检查正确的输出后,删除大写的ECHO命令!

如果两个名称文件中出现以下任何字符,则此方法无效:=!^~不得在第一个文件(旧名称)的任何行中作为第一个字符出现。

答案 1 :(得分:1)

根据我的评论。创建一个名为names.txt的文件,并添加您要替换的字符串以及您要替换的字符串:

dummy replacement
dummy2 replacement2

然后该脚本需要位于同一目录中,否则您必须指定文件的路径:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2" %%i in (names.txt) do (
  for /f %%a in ('dir /b /a-d ^| findstr "%%i"') do (
    set "oldname=%%a"
    set "newname=!oldname:%%i=%%j!"
    echo ren "!oldname!" "!newname!"
  )
)

或通过指定路径:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2" %%i in (names.txt) do (
  for /f %%a in ('dir /b /a-d "D:\PATH" ^| findstr "%%i"') do (
    set "oldname=%%a"
    set "newname=!oldname:%%i=%%j!"
    echo ren "!oldname!" "!newname!"
  )
)

一旦您满意地将其打印出要替换的文件以显示在屏幕上,请从代码的最后一行中简单地删除echo以实际执行ren

相关问题