Reputation:
I have this .txt
file:
Previsto: R$ 9.766,53
Previsto: R$ 423,65
Previsto: R$ 514,51
Previsto: R$ 492,63
So i need change the word "Previsto" to another word, like it:
Visa: R$ 9.766,53
Elo: R$ 423,65
Hipercard: R$ 514,51
Sorocred: R$ 492,63
I did this .bat
script:
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=%Previsto"
set "replace=%Visa"
set "textFile=extract.txt"
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
But all line are replacing "Previsto" to "Visa" I don't know how to set it to change only the fisrt line to "Visa" the second line "Elo", thrid "Hipercard", etc.
How can i do it?
Thanks
Upvotes: 0
Views: 71
Reputation: 9545
Try like this :
@echo off
setlocal enabledelayedexpansion
set "$file=extract.txt"
set "$search=Previsto"
set $repl[1]=Visa
set $repl[2]=Elo
set $repl[3]=Hipercard
set $repl[4]=Sorocred
set $count=1
(for /f "delims=" %%a in (%$file%) do (
call:replace "%%a" !$count!
set/a $count+=1
)
)>out.txt
echo done..
exit/b
:replace
set "$line=%~1"
set $repl=!$repl[%2]!
set "$line=!$line:%$search%=%$repl%!"
echo !$line!
The ouput file is out.txt
Edit 2
for the blank line after line 1
:replace
set "$line=%~1"
set $repl=!$repl[%2]!
set "$line=!$line:%$search%=%$repl%!"
echo !$line!
if "%2"=="1" echo.
Upvotes: 1
Reputation:
I had a similar idea as SachaDee but a different approach on creating an array and without a subroutine
:: Q:\Test\2018\06\04\SO_50684988.cmd
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Rem Set replace[0..3] to cards
Set i=-1&Set "replace= Visa Elo Hipercard Sorocred"
Set "replace=%replace: ="&Set /a i+=1&Set "replace[!i!]=%"
set "search=Previsto"
set "textFile=extract.txt"
set /A "cnt=pnt=0,i+=1"
(for /f "tokens=1* delims=:" %%A in ('type "%textFile%" ') do (
if /i "%%A" equ "%search%" call Echo=%%replace[!pnt!]%%:%%B
if !pnt!==0 Echo=
Set /A "cnt+=1,pnt=cnt %% i"
) ) >"New_%textFile%
type "New_%textFile%"
Sample output with a blank line following visa:
>SO_50684988.cmd
Visa: R$ 9.766,53
Elo: R$ 423,65
Hipercard: R$ 514,51
Sorocred: R$ 492,63
The batch would replace any number of Previsto in turn with the replacements.
Upvotes: 1