Sandra
Sandra

Reputation: 13

Batch modifying text at specific line

I should:

1) remove a whole line which is like

HYDRAULICS blabla

I thought to use

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

but in the file.ext it is written also the not needed

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

2) add, before lines which start with IF , a line containg the short phrase RULE 1 (the first time, RULE 2 the second and so on). I have the text

[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  

but I want it to become

[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  

Upvotes: 0

Views: 46

Answers (2)

foxidrive
foxidrive

Reputation: 41234

For part 2) this uses a mixture of old and new techniques - the input file is file.txt and the output file is newfile.txt

It can be simplified by used delayed expansion.

@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

This is a reformatted section - which Sandra seemed to say was more readable.

@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

Upvotes: 1

foxidrive
foxidrive

Reputation: 41234

The extra line doesn't appear when redirection is used.

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

Upvotes: 0

Related Questions