You can do it by using for
loop to move through each line of the file, and when you find the line with the 'Description', you append '_V2' to the output.
@echo off
for %%f in (*.txt) do (
for /f "tokens=1* delims=:" %%g in ('type "%%f" ^| findstr /n /v "BoGuSsTrInG"') do (
if "%%hx"=="x" (
echo.>>"%%~nf.newtxt"
) else (
for /f "tokens=1* delims==" %%i in ('echo.%%h') do (
if "%%i"=="Description" (
echo.%%i=%%j_V2>>"%%~nf.newtxt"
) else (
if "%%jx"=="x" (
echo.%%i>>"%%~nf.newtxt"
) else (
echo.%%i=%%j>>"%%~nf.newtxt"
)
)
)
)
)
)
ren *.txt *.oldtxt
ren *.newtxt *.txt
Of course, you have to output the content to a new file while you process the test.txt
file. Then you replace the original file with the newly created one...
Edit #1
You have to copy the contents of the TXT files to new files completely before you rename any of them back to their original names. This is because the for
loop will pick them up again after they are modified if you immediately rename them and some of them will get the _V2
appended several times.
I did not remove the .oldtxt
files at the end, because you should never destroy your original files until you know that the process worked!
Edit #2
There is one workaround that I found that will preserve the blank lines. The workaround pipes the content of the text file to findstr
, searching for all lines that don't contain BoGuSsTrInG
. The output includes the line numbers (the only way to get it to print the blank lines). The line numbers have a trailing colon (:
), so we can divide the output into different variables splitting the content on the colon. The tokens=1*
split the line number into the %%g
variable, and the result of the line is in the %%h
variable. We can test %%h
to see if it is empty and add a blank line to the new file. Otherwise, we process %%h
as before.