Edit text in file with batch

1

I have to replace a line within a txt with batch and I need help with the code ... I have the files test.txt and test2.txt the objective is to move from file 1 to file 2 with the same content unless it contains a specific word, in which case, the entire line must be replaced by a predefined one.

I specifically have problems with the 'if' and with the reassignment of the variable.

>@echo off

>setlocal enabledelayedexpansion

>set p1=prueba.txt

>set p2=prueba2.txt


>for /f "tokens=*" %%a in (%p1%) do (

>    set nl=%%a

>    if not "%n1%"=="%n1:texto=%" (

>        set n1=este texto esta mejor

>    )

>    echo !n1! >> %p2%

>)

>pause>nul

>exit

Thank you very much for your help

    
asked by Juan Comande 10.07.2018 в 03:35
source

1 answer

0

This script should work:

@echo off

setlocal enabledelayedexpansion

set p1=prueba.txt
set p2=prueba2.txt

copy NUL %p2% 1>NUL 2>&1
for /f "tokens=*" %%a in (%p1%) do (
  set n1=%%a
  if not "!n1!"=="!n1:texto=!" (
    set n1=este texto esta mejor
  )
  echo !n1! >> %p2%
)

pause>nul
exit

What I have corrected:

In some sites references to "n1" and in others "nl" (it was an 'errata')

Within the loop, you should reference the variable n1 as !n1! instead of %n1% this is because you are updating it within the loop, but in batch you always recover the previous value unless you use setlocal enabledelayedexpansion and referencies to the variables with !!

Finally I added copy NUL %p2% 1>NUL 2>&1 before the for to empty the destination file. If not, in case you use the script several times, you will duplicate the content of the lines. If you're not interested, you can delete this line.

I hope it serves you.

    
answered by 31.07.2018 в 09:03