Search code examples
windowsbatch-fileechodouble-quotes

escape double quotes in a variable when using echo|set /p=


echo|set /p= can output a variable without a newline.

I am trying to loop a text file like this

for /f %%a in (zen.txt) do (
    set var=%%a
    echo !var!
    echo|set /p=!var!
)

There are some lines with only one ", for example:

"he said...

echo outputs the line like above correctly while echo|set /p= output nothing.

Is it possible to escape double quotes in a variable when using echo|set /p=.


Solution

  • We will need to provide set/p with additional quotes to consume. You can try with something like (without the test file creation, of course)

    @echo off
        setlocal enableextensions disabledelayedexpansion
    
        rem TESTING - Create a input file
        >zen.txt (
            echo "He said...
            echo It was not me!
            echo It was "the thing"!
            echo ...
            echo ^& it was all"  ( The end )
        )
    
        for /f "delims=" %%a in (zen.txt) do (
            <nul set /p="%%a "
        )
    

    echo|set /p simulates a return key press to terminate the set/p prompt, but it creates separate cmd instances for each side of the pipe making it slow. A <nul input redirection is enough to get the same result but faster and with less resources usage.