Search code examples
batch-filequotes

Trouble in Batch using quotes in a variable


Relatively new to batch scripts here and I have been searching everywhere for the answer only to not find anything.

Here is what I have for a batch script so far..

@echo off

set addtext="text to add includes spaces"

for /f "delims=" %%l in (file.txt) do (
    echo %%l %addtext% >> tmpfile.txt
)

I'm looking to add a line of text to every line in the file but my problem comes in with the double quotes. I don't want the quotes to display with the text.
I only have the quotes there because there are spaces in the string of text that I'm looking to add to every line.


Solution

  • @echo off
        setlocal enableextensions disabledelayedexpansion
        set "addtext=text to add includes spaces"
    
        for /f "delims=" %%l in (file.txt) do (
            >> tmpfile.txt echo %%l %addtext%
        )
    

    This should work. Just not include the quotes in the value of the variable, but use them to wrap the assignment.

    In cases where the string could contain more problematic characters, this is a safer version

    @echo off
        setlocal enableextensions disabledelayedexpansion
        set "addtext=text to add includes spaces, > redirections & more problems !"
    
        (for %%a in ("%addtext%") do for /f "delims=" %%l in (file.txt) do (
            echo %%l %%~a
        )) >> tmpfile.txt 
    
    1. Quotes are not included in the value, but wraps the assignation
    2. To prevent problem accessing the variable, it is wrapped in quotes, stored in a for replaceable parameter (%%a) and when requested echoed without the quotes (%%~a)
    3. Just to get better performance (should be used also in the first code) instead of open/write/close the output file for each line (redirection for each echo), redirection is handled for the full for command.