批量修改特定行的文本

Batch modifying text at specific line

我应该:

1) 删除一整行,如

HYDRAULICS blabla

我想用

find /V "HYDRAULICS"....>path\file.ext

但在file.ext中也写了不需要的

---------- path\file.ext

2) 在以 IF 开头的行之前添加包含短短语 RULE 1 的行(第一次,RULE 2 第二次,依此类推)。 我有文字

[RULES]
;Text
;-----------------------------
IF TANK T1421 LEVEL BELOW 1 THEN PUMP PT395&395dn STATUS IS OPEN                                     
IF TANK T1421 LEVEL ABOVE 3 THEN PUMP PT395&395dn STATUS IS CLOSED                                   
IF TANK T395 LEVEL BELOW 1 THEN PUMP PFALDA395&T395 STATUS IS OPEN                                   
IF TANK T395 LEVEL ABOVE 4 THEN PUMP PFALDA395&T395 STATUS IS CLOSED  

但我希望它变成

[RULES]
;Text
;-----------------------------
RULE 1
IF TANK T1421 LEVEL BELOW 1 THEN PUMP PT395&395dn STATUS IS OPEN                                     
RULE 2
IF TANK T1421 LEVEL ABOVE 3 THEN PUMP PT395&395dn STATUS IS CLOSED                                   
RULE 3
IF TANK T395 LEVEL BELOW 1 THEN PUMP PFALDA395&T395 STATUS IS OPEN                                   
RULE 4
IF TANK T395 LEVEL ABOVE 4 THEN PUMP PFALDA395&T395 STATUS IS CLOSED  

使用重定向时不会出现额外的行。

find /V "HYDRAULICS" <"filein.txt" >"path\file.ext"

2) 部分混合使用了新旧技术 - 输入文件为 file.txt,输出文件为 newfile.txt

可以通过使用延迟扩展来简化。

@echo off
del "%temp%\counter.txt" 2>nul
(
for /f "eol=| usebackq delims=" %%a in ("file.txt") do (
   for /f  %%b in ("%%a") do ( if /i "%%b"=="IF" echo .>>"%temp%\counter.txt"
           for /f %%c in ('find /c "." ^<"%temp%\counter.txt" ') do echo RULE %%c
   )
echo %%a
)
)>"newfile.txt"
del "%temp%\counter.txt" 2>nul

这是一个重新格式化的部分 - Sandra 似乎说它更具可读性。

@echo off
del "%temp%\counter.txt" 2>nul
(
for /f "eol=| usebackq delims=" %%a in ("file.txt") do (
   for /f  %%b in ("%%a") do (
      if /i "%%b"=="IF" (
          echo .>>"%temp%\counter.txt"
             for /f %%c in ('find /c "." ^<"%temp%\counter.txt" ') do echo RULE %%c
       )
   )
echo %%a
)
)>"newfile.txt"
del "%temp%\counter.txt" 2>nul