0

I am reading a file line-by-line and I only want to print a specific type of line.

This is my sample input:

this
is a test line
this shouldn't
be
printed
but
(c) one[1]
(c) one[2]
the above 2 lines should

This is my code:

set c="(c) one["
set s="two["

echo "start">"./output.txt"

for /f "tokens=*" %%s in (input.txt) do (
    echo.%%s | findstr /C:%c%
    if %errorlevel%==0 echo %%s>>"./output.txt"
)

This reads the file line-by-line, but the findstr line is always throwing %errorlevel% of 1.

Console output:

XXX\Desktop\test>e

XXX\Desktop\test>set c="(c) one["

XXX\Desktop\test>set s="two["

XXX\Desktop\test>echo "start" 1>"./output.txt"

XXX\Desktop\test>for /F "tokens=*" %s in (input.txt) do (
echo.%s   | findstr /C:"(c) one["
 if 1 == 0 echo %s 1>>"./output.txt"
)

XXX\Desktop\test>(
echo.this   | findstr /C:"(c) one["
 if 1 == 0 echo this 1>>"./output.txt"
)

XXX\Desktop\test>(
echo.is a test line   | findstr /C:"(c) one["
 if 1 == 0 echo is a test line 1>>"./output.txt"
)

XXX\Desktop\test>(
echo.this shouldn't   | findstr /C:"(c) one["
 if 1 == 0 echo this shouldn't 1>>"./output.txt"
)

XXX\Desktop\test>(
echo.be   | findstr /C:"(c) one["
 if 1 == 0 echo be 1>>"./output.txt"
)

XXX\Desktop\test>(
echo.printed   | findstr /C:"(c) one["
 if 1 == 0 echo printed 1>>"./output.txt"
)

XXX\Desktop\test>(
echo.but   | findstr /C:"(c) one["
 if 1 == 0 echo but 1>>"./output.txt"
)

XXX\Desktop\test>(
echo.(c) one[1]   | findstr /C:"(c) one["
 if 1 == 0 echo (c) one[1] 1>>"./output.txt"
)
(c) one[1]

XXX\Desktop\test>(
echo.(c) one[2]   | findstr /C:"(c) one["
 if 1 == 0 echo (c) one[2] 1>>"./output.txt"
)
(c) one[2]

XXX\Desktop\test>(
echo.the above 2 lines should   | findstr /C:"(c) one["
 if 1 == 0 echo the above 2 lines should 1>>"./output.txt"
)

XXX\Desktop\test>

My output is just "start". Nothing else. Where am I going wrong?

NOTE: The batch file ran the very first time but printed all the lines. Second time onwards it's printing nothing.

SonOfEl
  • 175
  • 1
  • 9
  • 3
    Does this answer your question? [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected) Specifically, because `%errorlevel%` gets set and used inside of the same set of parentheses, you need to add `setlocal enabledelayedexpansion` to the top of your script and use `!errorlevel!` instead of `%errorlevel%`. – SomethingDark Feb 25 '22 at 09:48

0 Answers0