在 Windows 批处理文件中转义 & 符号

发布于 2024-09-30 03:10:24 字数 387 浏览 0 评论 0原文

我意识到您可以使用帽子字符在批处理文件中转义&符号,

例如

echo a ^& b
a & b

但我使用的命令

for /f "tokens=*" %%A IN ('DIR /B /A-D /S .acl') DO ProcessACL.cmd "%%A"

是在当前目录或当前目录的子目录中查找所有名为“.acl”的文件。

问题是,我正在查找包含“&”的路径名字符(不,它们不能重命名),我需要一种自动转义&符号并使用转义路径作为参数调用第二个批处理文件的方法。

rem ProcessACL.cmd
echo %1

I realise that you can escape ampersands in batch files using the hat character

e.g.

echo a ^& b
a & b

But I'm using the command

for /f "tokens=*" %%A IN ('DIR /B /A-D /S .acl') DO ProcessACL.cmd "%%A"

which is finding all the files named '.acl' in the current directory, or a subdirectory of the current directory.

The problem is, I'm finding path names that include the '&' character (and no, they can't be renamed), and I need a way of automatically escaping the ampersands and calling the second batch file with the escaped path as the parameter.

rem ProcessACL.cmd
echo %1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

删除→记忆 2024-10-07 03:10:24

问题不在于转义,它似乎在第二个脚本中。

如果有一行像

echo %1

Then it is Expands and Failure:

echo You & me.acl

Better to use Lately Expansion like

setlocal EnableDelayedExpansion
set "var=%~1"
echo !var!

为了避免参数中出现感叹号 ! 问题,第一个 set 应该是在 DisableDelayedExpansion 上下文中使用。

setlocal DisableDelayedExpansion
set "var=%~1"
setlocal EnableDelayedExpansion
echo !var!

The problem is not the escaping, it seems to be in the second script.

If there is a line like

echo %1

Then it is expands and fails:

echo You & me.acl

Better to use delayed expansion like

setlocal EnableDelayedExpansion
set "var=%~1"
echo !var!

To avoid also problems with exclamation points ! in the parameter, the first set should be used in a DisableDelayedExpansion context.

setlocal DisableDelayedExpansion
set "var=%~1"
setlocal EnableDelayedExpansion
echo !var!
恬淡成诗 2024-10-07 03:10:24

您的 for 行应该是(注意 *.acl)

for /f "tokens=*" %%A IN ('DIR /B /A-D /S *.acl') DO ProcessACL.cmd "%%A"

ProcessACL.cmd 可以使用 %1 访问传递给它的路径。

// ProcessACL.cmd
ECHO %1

变量 %1 包含的内容均已完全包含。没有必要逃避。转义符用于批处理器解释它正在解析的字符。

Your for line should be (note the *.acl)

for /f "tokens=*" %%A IN ('DIR /B /A-D /S *.acl') DO ProcessACL.cmd "%%A"

ProcessACL.cmd can access the path passed to it with %1.

// ProcessACL.cmd
ECHO %1

Whatever is contained by the variable %1 is fully contained. There is no need for escapes. Escapes are for the batch processor to interpret the characters it is parsing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文