2014-03-25 81 views
5
for /f "delims=" %%a in ('"%systemRoot%\system32\find.exe" /?') do @echo %%a 

是的,上一行工作正常。没有太大的作用,但有效。但是,试图写一个批处理文件来回答另一个问题,我面对像windows cmd:带有带引用参数的带引号的命令的for/f问题

for /f %%a in ('"%systemRoot%\system32\find.exe" /c /v "" ^< "c:\something.txt"') do @echo %%a 
for /f %%a in ('"%systemRoot%\system32\find.exe" /c /v "" "c:\something.txt"') do @echo %%a 

无论是以前行返回The filename, directory name, or volume label syntax is incorrect

for /f %%a in ('"%systemRoot%\system32\find.exe" /c /v "" ^< c:\something.txt' ) do @echo %%a 
for /f %%a in ('"%systemRoot%\system32\find.exe" /c /v "" c:\something.txt' ) do @echo %%a 

无论是以前行返回The system cannot find the file specified

我已经无法使其工作,既没有引用报价,也没有将它们加倍,在反斜杠前改为单引号以反引号,并在for命令中设置相应选项,所有combinati我尝试失败。

如果要运行的命令被引用并且需要带引号的参数,则失败。

是的,我知道引号surounding不需要的find,如果删除,任何先前的四大行就可以了(忽略输出,delims,代币)

但在情况下报价完全需要围绕命令(并且我知道8dot3name行为被禁用的系统),有什么方法可以使其工作?我在这里错过了什么?

回答

7

这里有两个解决方案。

1)有周围的双引号,并删除^转义字符。
2)使用查找,因为它是在路径上。

for /f %%a in ('""%systemRoot%\system32\find.exe" /c /v "" < "c:\something.txt""') do @echo %%a 

for /f %%a in (' find.exe /c /v "" ^< "c:\something.txt"') do @echo %%a 

这与启动额外的cmd进程以在for命令内运行命令行有关。

奇怪的是,这三个命令在更简单的上下文中失败了。

for /f %%a in (' "c:\windows\system32\find.exe" /c /v "" something.txt ') do @echo %%a 

系统找不到指定的路径。

for /f %%a in (' "c:\windows\system32\findstr.exe" /n "." something.txt ') do @echo %%a 

目录名称无效。

for /f %%a in (' "c:\windows\notepad" "something.txt" ') do @echo %%a 

“C:\ WINDOWS \记事本”,“something.txt”不被识别为一个内部或外部的命令,可操作的程序或批处理文件。

这最后一个提供了外部引号被剥离的线索。

的Windows 8.1 32位

我想在这里说明在cmd /?报价问题,当调用一个子进程:

If /C or /K is specified, then the remainder of the command line after 
the switch is processed as a command line, where the following logic is 
used to process quote (") characters: 

    1. If all of the following conditions are met, then quote characters 
     on the command line are preserved: 

     - no /S switch 
     - exactly two quote characters 
     - no special characters between the two quote characters, 
      where special is one of: &<>()@^| 
     - there are one or more whitespace characters between the 
      two quote characters 
     - the string between the two quote characters is the name 
      of an executable file. 

    2. Otherwise, old behavior is to see if the first character is 
     a quote character and if so, strip the leading character and 
     remove the last quote character on the command line, preserving 
     any text after the last quote character. 
+2

+1当然!!我忘了!该命令在新的cmd实例内运行。谢谢。我无法看到这一点。在这种情况下,第二个选项(路径)被丢弃,因为原始问题似乎与干扰执行的非本地'find'命令有关。 –

+2

为了避免扰乱命令中的引用行为:'in('^“”some cmd.exe“”some | arg“^”')''这可能是一个好主意。另外,我不记得任何细节,但我相信MS文档中有一个小小的缺陷 - 我不认为它完全描述了报价行为。 – dbenham

0

这是比较容易把第一令牌从指令for循环到不带引号的令牌中。

for /f "delims=" %%a in (
' if defined OS "C:\my folder with spaces\consoleapp.exe" /param1:"value" ' 
)do @echo %%a