Reputation: 11
I am using below mentioned code for finding a string in a file(Constants.TcGVL), assign my desired value(%select%) to it and copy to a new location:
Call :ValueSubstitude "%root%\LeafSpring\Constants.TcGVL" "%root%\LeafSpring\GVLs\Constants.TcGVL" "%select%"
:ValueSubstitude
@echo off
SETLOCAL ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
Set "Tag1=nNrOfInstances : UINT := "
Set "Tag2=%~3"
for /f "delims=" %%a in (%~1) do (
Set "str=%%a"
setLocal EnableDelayedExpansion
Set str=!str:%Tag1%=%Tag1%%Tag2%!
echo !str!>>"%~2"
ENDLOCAL
)
Exit /B 0
Original file has string like this:
nNrOfInstances : UINT := 3;
Now my %select% value could be 1, 2 ,3...and I want to replace '3' in above line with my desired number but the output I am getting is wrong.
The output looks like this:
=nNrOfInstances : UINT := 1= 3;
It has a space and equal sign at start of line and = 3 at the end. It has my desire number in it which is 1 but also the earlier value = 3 which should not be there.
Kindly assist me getting the right output or let me know what am I doing wrong here. Thank you.
Upvotes: 1
Views: 51
Reputation: 79947
@ECHO OFF
SETLOCAL
SET "tag2=2"
Set "Tag1=nNrOfInstances : UINT := "
for /f "delims=" %%e in (q77984148.txt) do (
ECHO %%e|FINDSTR /b /L /c:"%tag1%" >NUL
IF ERRORLEVEL 1 (ECHO %%e) ELSE (
ECHO %tag1%%tag2%;)
)
I used a file named q77984148.txt
containing your data and some junk data for my testing.
The replacement processing uses findstr
to see whether the line read (in %%e
) begins with (/b
) the literal string (/L
) constant (/c:"this string"
), and suppressing the output (>nul
). This sets errorlevel
to 0 if found and 1 if not.
If the resultant errorlevel
is 1
or greater, simply echo
the line, else (the string was found) so reconstruct the line (including the terminal ;
which appears to have become lost in your narrative)
Note that the construction
(
for....do.(
....
)
)>filename
will recreate filename
with the contents of (whatever the for
loop outputs).
Naturally >>filename
will append this data to an existing file filename
or create that file if it doesn't already exist
Upvotes: 2