@ECHO OFF
SETLOCAL
:: Replace token 2 (space-separated) in line 5 of a file with REPLACEMENT
:: Assumed the file exists, etc. and no line begins ":"
SET replacement=THIS IS THE REPLACEMENT TEXT
DEL newfile.txt 2>nul
FOR /f "tokens=1*delims=:" %%i IN ('findstr /n /r "$" ^<oldfile.txt') DO (
IF %%i==5 (
FOR /f "tokens=1,2* delims= " %%L IN ("%%j") DO >>newfile.txt ECHO %%L %replacement% %%N
) ELSE (>>newfile.txt ECHO.%%j)
)
TYPE oldfile.txt
ECHO ==== separator =======
FC oldfile.txt newfile.txt
結果:
Line one should not be changed
Line two should not be changed
Line three should not be changed
Line four should not be changed
changeme iwillbereplaced but only on this line
and notbereplaced on subsequent lines
including the previous line which was empty
==== separator =======
Comparing files oldfile.txt and NEWFILE.TXT
***** oldfile.txt
Line four should not be changed
changeme iwillbereplaced but only on this line
and notbereplaced on subsequent lines
***** NEWFILE.TXT
Line four should not be changed
changeme THIS IS THE REPLACEMENT TEXT but only on this line
and notbereplaced on subsequent lines
*****
有困難 - 特別是如果你的文件中的行以冒號或包含引號的字符串或任何常規的一批陷阱像%
所以 - 最後我已經弄清楚你在做什麼。您省略了關鍵信息,即%%F
中的字符串不僅被引用,還包含空格。
你有沒有說過,首先,你會在你的項目中做更多的工作,而且我會更加富有一些阿司匹林。
爲了用加引號的字符串加載%% F,我從文件中讀取了字符串。
@ECHO OFF
SETLOCAL enabledelayedexpansion
:: Replace token 2 (space-separated) in line 5 of a file with REPLACEMENT
:: Assumed the file exists, etc. and no line begins ":"
SET replacement="THIS IS THE REPLACEMENT TEXT"
DEL newfile.txt 2>NUL
:: iwbr.txt just contains
:: "i will be replaced"
:: on a single line for loading into %%F as that is the target to be replaced
FOR /f "delims=" %%F IN (iwbr.txt) DO (
FOR /f "tokens=1*delims=:" %%i IN (
'findstr /n /r "$" ^<oldfile.txt'
) DO >>newfile.txt (
IF %%i==5 (
SET newline=%%j
CALL SET newline=%%newline:%%F=%replacement%%%
ECHO.!newline!
) ELSE (ECHO.%%j)
)
)
TYPE oldfile.txt
ECHO ==== separator =======
FC oldfile.txt newfile.txt
結果:
Line one should not be changed
Line two should not be changed
Line three "should" not be changed
Line four should not be changed
changeme "i will bereplaced" but only on this line
and notbereplaced on subsequent lines
including the "previous" line which was empty
including this "unbalanced-quote line...
==== separator =======
Comparing files oldfile.txt and NEWFILE.TXT
***** oldfile.txt
Line four should not be changed
changeme "i will bereplaced" but only on this line
and notbereplaced on subsequent lines
***** NEWFILE.TXT
Line four should not be changed
changeme "THIS IS THE REPLACEMENT TEXT" but only on this line
and notbereplaced on subsequent lines
*****
你會* *得多更好寫* *任何像這樣在VBScript。或Powershell。或Perl。 *任何*但.bat文件。恕我直言... – paulsm4 2013-03-21 05:39:49
我更熟悉批次atm。謝謝。 – 2013-03-21 05:40:35
paulsm如何與VBScript批量交換變量?我批量使用了所有變量,但是如何將它們轉換爲vbscript? – 2013-03-21 05:44:52