@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
*****