How do you strip quotes out of an ECHO'ed string in a Windows batch file?

后端 未结 12 1890
萌比男神i
萌比男神i 2020-12-05 04:23

I have a Windows batch file I\'m creating, but I have to ECHO a large complex string, so I\'m having to put double quotes on either end. The problem is that the quotes are

12条回答
  •  不知归路
    2020-12-05 05:00

    Using the FOR command to strip the surrounding quotation marks is the most efficient way I've found to do this. In the compact form (Example 2) it's a one-liner.

    Example 1: The 5-line (commented) solution.

    REM Set your string
    SET STR="     (Optional) If specified this is the name of your edited file"
    
    REM Echo your string into the FOR loop
    FOR /F "usebackq tokens=*" %%A IN (`ECHO %STR%`) DO (
        REM Use the "~" syntax modifier to strip the surrounding quotation marks
        ECHO %%~A
    )
    

    Example 2: The 1-liner real-world example.

    SET STR="     (Optional) If specified this is the name of your edited file"
    
    FOR /F "usebackq tokens=*" %%A IN (`ECHO %STR%`) DO @ECHO %%~A
    

    I find it interesting that the inner echo ignores the redirection characters '<' and '>'.
    If you execute ECHO asdfsd>asdfasd you will write file out instead of std out.

    Hope this helps :)

    Edit:

    I thought about it and realized there is an even easier (and less hacky) way of accomplishing the same thing. Use the enhanced variable substitution/expansion (see HELP SET) like this:

    SET STR="     (Optional) If specified this is the name of your edited file"
    
    ECHO %STR:~1,-1%
    

    That will print all but the first and last characters (your quotation marks). I would recommend using SETLOCAL ENABLEDELAYEDEXPANSION too. If you need to figure out where quotation marks are located in the string you can use FINDSTR to get the character #s.

提交回复
热议问题