@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q64587777.txt"
:: I'll just use a fixed string for the IPaddress
set "IPaddress=User-input IP address"
:: remove variables starting #
FOR /F "delims==" %%a In ('set # 2^>Nul') DO SET "%%a="
FOR /f "tokens=1*delims=:" %%a IN (
'findstr /v /N /L /C:"storage.app.lab" /C:"home.app.lab" /C:"api.app.lab" "%filename1%"'
) DO set "#%%a=%%b"
(
FOR /F "tokens=1*delims==" %%a In ('set # 2^>Nul') DO echo %%b
for %%a in ("storage.app.lab" "home.app.lab" "api.app.lab") do echo %IPaddress% %%~a
)>"%filename1%"
GOTO :EOF
You would need to change the setting of sourcedir
to suit your circumstances. The listing uses a setting that suits my system.
I used a file named q64587777.txt
containing some dummy data for my testing.
The first few lines simply establish filename variables for testing, and a recognisable string to save re-entering data in testing.
The procedure will use variables named #*
for temporary storage of the "other" lines in the file in question, so first clear out any variables that may exist that start #
.
Then execute findstr
and "print" lines that do NOT contain (/V
) any of the /L
literal strings provided as /c:"string-to-EXclude"
and /N
number thos lines with a leading serial number followed by a colon.
The for /f
tokenises the line using the :
separator as a delimiter and assigning the line number to %%a
(token 1) and the remainder of the line (the data in question) to %%b
. Set the environment variable #%%a
to the lines found.
Then use the same principle on a set #
list, which will list all variables starting #
in the format #1=line one
, delimiting on =
and selecting the 2nd token, which is the line data originally read from the file.
And add the three new lines by construction.
Parenthesising the two for
statements together gathers the echo
ed output which is then redirected to the original file, overwriting it.
Note that OP's code appended the (up to) three new lines. The requirement is (apparently) that the 3 lines will appear in the file, replacing any existing data for those three entries.