如何在Windows批处理文件中转义保留的字符 [英] How to escape reserved characters in Windows batch files

查看:381
本文介绍了如何在Windows批处理文件中转义保留的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理文件名列表,但是不知道如何转义"命令行以产生一致的输出,而不管该名是否包含纯文本或特殊字符(例如&"号,感叹号和百分比)标志.如果我在以下名称为四个示例文件上运行代码(如下):

I'm trying to process a list of file names but don't know how to "escape" the command line to produce consistent output regardless of whether the name contains plain text or special characters like the ampersand, exclamation point and percent sign. If I run my code (below) on four sample files whose names are:

01 A Test.txt
02 & Test.txt
03 ! Test.txt
04 % Test.txt

输出为:

1 "01 A Test.txt"
2 "02 & Test.txt"
 "03 COUNT
4 "04Test.txt"

带有纯文本和与号的文件名可以正确传递(只要它们用引号引起来即可),但是感叹号和百分号会产生完全不同的结果.如何将变量传递给子例程,以便对所有四种情况进行相同的处理(如果可能,将引号从输出中删除)?谢谢.

The file names with the plain text and the ampersand pass through correctly (as long as they're enclosed in quotation marks, that is) but the exclamation point and percentage sign produce entirely different results. How can I pass the variables through to the subroutine so all four cases get processed the same (with the quotation marks removed from the output, if possible)? Thank you.

:: CODE
:: ----
@echo off
setlocal EnableDelayedExpansion
set /a COUNT=0
for /f "tokens=*" %%g in ('dir /b *.txt') do (
  set /a COUNT=!COUNT! + 1
  call :LIST "%%g" !COUNT!                )
pause > nul
exit

:LIST
echo %2 %1
goto :EOF

推荐答案

尝试一下:

@echo off
setlocal EnableDelayedExpansion
set /a COUNT=0
for /f "tokens=*" %%g in ('dir /b *.txt') do (
  set /a COUNT=!COUNT! + 1
  <nul set /p=!count!
  setlocal disableDelayedExpansion & (
    (echo( %%g)
  )
  setlocal enableDelayedExpansion

)

您可以在for循环中打开/关闭延迟扩展,以正确地回显特殊字符. <nul set /p=%%g打印的字符串末尾没有换行符-这是正确计数应该在延迟扩展部分中的计数所必需的,并且无需子例程也可以更快地工作.

You can turn on/off the delayed expansion within the for loop for proper echoing the special chars. <nul set /p=%%g prints a string without new line at the end - which is needed for proper echoing of the count which should be in delayed expansion part.And it will work faster without subroutine.

已编辑以首先打印计数.

Edited to print the count first.

这篇关于如何在Windows批处理文件中转义保留的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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