在Windows批处理脚本处理报价 [英] Dealing with quotes in Windows batch scripts

查看:121
本文介绍了在Windows批处理脚本处理报价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows批处理文件,当你做到以下几点:

In a Windows batch file, when you do the following:

设置MYVAR =C:\\我的音乐和影片

变量 MYVAR 存储用引号包括在内。老实说,我觉得这很愚蠢。引号只是告诉其中字符串的开头和结尾,而不是被存储为价值本身的一部分。

我怎样才能prevent这种情况的发生?

the variable myvar is stored with the quotes included. Honestly I find that very stupid. The quotes are just to tell where the string begins and ends, not to be stored as part of the value itself.
How can I prevent this from happening?

感谢。

推荐答案

这取决于你想如何使用变量。如果你只是想使用的变量的值,不包括引号,你可以使用延迟扩展和字符串替换,或命令:

It depends on how you want to use the variable. If you just want to use the value of the variable without the quotes you can use either delayed expansion and string substitution, or the for command:

@echo OFF
SETLOCAL enabledelayedexpansion

set myvar="C:\my music & videos"

由于andynormancx状态,需要加引号,因为该字符串包含&安培; 。或者你可以用 ^ 逃吧,但我认为行情是​​干净了一点。

As andynormancx states, the quotes are needed since the string contains the &. Or you can escape it with the ^, but I think the quotes are a little cleaner.

如果您使用字符串替换延迟扩展,你得到的变量的值不带引号:

If you use delayed expansion with string substitution, you get the value of the variable without the quotes:

@echo !myvar:"=!
>>> C:\my music & videos

您也可以使用命令:

for /f "tokens=* delims=" %%P in (%myvar%) do (
    @echo %%P
)
>>> C:\my music & videos

不过,如果你想使用的变量在命令中,必须使用带引号的值或附上变量的引用值:

However, if you want to use the variable in a command, you must use the quoted value or enclose the value of the variable in quotes:


  1. 使用字符串替换和延迟扩展使用不带引号变量的值,但在命令中使用的变量:

  1. Using string substitution and delayed expansion to use value of the variable without quotes, but use the variable in a command:

@echo OFF
SETLOCAL enabledelayedexpansion


set myvar="C:\my music & videos"
md %myvar%
@echo !myvar:"=! created.


  • 使用命令使用变量的不带引号的价值,但你必须在命令中使用时,它用引号括变量:

  • Using the for command to use the value of the variable without quotes, but you'll have to surround the variable with quotes when using it in commands:

    @echo OFF
    set myvar="C:\my music & videos"
    
    
    for /f "tokens=* delims=" %%P in (%myvar%) do (
        md "%%P"
        @echo %%P created.
    )
    


  • 长话短说,有真正使用包含嵌入的空格的路径或文件名没有干净的方式和/或&放大器; S IN批处理文件

    Long story short, there's really no clean way to use a path or filename that contains embedded spaces and/or &s in a batch file.

    这篇关于在Windows批处理脚本处理报价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆