簡體   English   中英

BATCH - 在文本文件中查找字符串並在該行之后添加一個新字符串

[英]BATCH - Find string in text file and add a new string after that line

我正在嘗試從 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. 當我在命令提示符控制台中運行發布的代碼時,我看到一個語法錯誤:

    ) 在這個時候出乎意料。

    顯然, NewURL的括號在循環中展開時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%%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM