BATCH - 在文本文件中查找字符串,并在该行之后添加新字符串

时间:2015-10-11 21:43:02

标签: string batch-file echo

我试图从bat文件中搜索文本文件中的特定字符串。如果字符串存在,请在下一行后面添加一个新字符串。我似乎无法使下面的代码正常工作。任何想法?

这是我在我的文本文件中搜索的字符串。 [/Script/MyGame.Mode]

这是文本文件的样子。

[/Script/Config.Mode]
Something here 1
Something here 2

[/Script/MyGame.Mode]
Something here 1
Something here 2

[/Script/Edit.Mode]
Something here 1
Something here 2

这就是我想要的样子。

[/Script/Config.Mode]
Something here 1
Something here 2

[/Script/MyGame.Mode]
RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum="")
Something here 1
Something here 2

[/Script/Edit.Mode]
Something here 1
Something here 2

这是我到目前为止的代码。

@echo off

:GETINFO
echo.
echo.
cls
echo.
echo Let's get some information for your config. 
echo Note: The information you enter below is case sensitive. You can copy and paste.
echo.
echo Here's a Package Name example: "DM-MyTest-WindowsNoEditor"
echo.
set /p Package=Enter Package Name:
echo.
echo.
echo.
echo The Package URL Protocol will be "http" or "https"
echo.
set /p PackageURLProtocol=Enter Package URL Protocol:
echo.
echo.
echo.
echo Here's a WebAddress example: "www.myredirect.com/test" (Don't add the trailing /)
set /p WebAddress=Enter Redirect(WebAddress)URL:
echo.
echo.
echo.
echo The file extention is usually ".pak"
echo.
set /p Ext=Enter Map File Extention:
echo.
cls
echo.
echo Please wait... Currently Creating Test References.

:SHOWLINE
echo.
set NewURL=RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum=""^^)

pause

:WRITENEW
set inputfile=game.txt
set outputfile=game.temp.txt
(for /f usebackq^ delims^=^ eol^=  %%a in ("%inputfile%") do (
   if "%%~a"=="[/Script/MyGame.Mode]" call echo %NewURL%
   echo %%a 
))>>"%outputfile%"

echo.
pause

1 个答案:

答案 0 :(得分:1)

  1. 当我在命令提示符控制台中运行发布的代码时,我看到语法错误:

      

    )此时出人意料。

    显然,NewURL中的括号在循环中展开时会破坏。

    • 一个简单的解决方案是使用call技巧延迟扩展:

      call echo %%NewURL%%
      
    • 可替换地:

      setlocal enableDelayedExpansion & echo !NewURL! & endlocal
      
    • 或者使用^^双重转义右括号(set一次,另一次转义为循环内的扩展值):

      set NewURL=.............PackageChecksum=""^^)
      
  2. 另一个问题是输出文件名与输入文件名相同,但是无法将输出重定向到您正在阅读的同一文件中。

    将输出名称更改为其他文件。然后在循环结束后更换原件:

    set inputfile=game.txt
    set outputfile=game.temp.txt
    ...................
    ))>>"%outputfile%"
    move/y "%outputfile%" "%inputfile%"
    
  3. 要改变新字符串的顺序,在找到的行之后打印它,只需交换内部循环中的两行:

    echo %%a 
    if "%%~a"=="[/Script/MyGame.Mode]" call echo %%NewURL%%