如何使用 .bat 文件将动态术语列表替换为计数?

问题描述 投票:0回答:1

目前这就是我正在尝试做的事情。我有一个文件 A 和一个文件 B。

文件 A 将包含一个术语列表,例如:

  • 文字
  • 文本2

文件 B 中将包含大量代码。此代码将包含 TEXT 和 TEXT2。

我需要分别用 :1 和 :2 替换 TEXT 和 TEXT2。当我在要替换的文本中进行硬编码时,我可以让它工作,但我确实需要它动态工作。

下面是将 TEXT 替换为 :1 的代码

SET count=1
for /F "tokens=*" %%A in (file_a.txt) do (
    call :subroutine %%A
)

:subroutine
    echo %count%:%1
    set "search=TEXT"
    set "replace=:%count%" 
    set /a count+=1

    set "textFile=file_b.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )
 GOTO :eof

echo %count%:%1 行正确输出:1:TEXT。为什么我无法更换以下行:

set "search=TEXT"

与:

set "search=%1"

当我这样做时,输出文件只有这样:

line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
line:=3:
windows batch-file
1个回答
0
投票

这就是我会做的方式:

@echo off
setlocal

rem Load the list of replacement words from file_a
set count=0
for /F %%a in (file_a.txt) do (
   set /A "repl[%%a]=count+=1"
)

rem Do the replacements in file_b
for /F "delims=" %%i in (file_b.txt) do (
   set "line=%%i"
   setlocal EnableDelayedExpansion
   for /F "tokens=2,3 delims=[]=" %%x in ('set repl') do (
      set "line=!line:%%x=:%%y!"
   )
   echo(!line!
   endlocal
)

输入示例:

Currently this is what I am trying to do. I have a file A and a file B.

File A will have a list of terms like:

TEXT
TEXT2

File B will have lots of code in it. This code will contain TEXT and TEXT2.

I need to replace TEXT and TEXT2 with :1 and :2 respectively. I can get this to work when I hard code in the TEXT to be replaced but I really need it to work dynamically.

Below is the code that will work to replace TEXT with :1

输出:

Currently this is what I am trying to do. I have a file A and a file B.
File A will have a list of terms like:
:1
:2
File B will have lots of code in it. This code will contain :1 and :2.
I need to replace :1 and :2 with :1 and :2 respectively. I can get this to work when I hard code in the :1 to be replaced but I really need it to work dynamically.
Below is the code that will work to replace :1 with :1

您只需要完成一些细微的调整...

© www.soinside.com 2019 - 2024. All rights reserved.