[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[文本处理] [已解决]批处理里面括号也需要转义吗?

在这段代码里,括号不转义的话,就会一闪而过
  1. @echo off
  2. (echo # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
  3. echo #
  4. echo # This file contains the mappings of IP addresses to host names. Each   
  5. echo # entry should be kept on an individual line. The IP address should
  6. echo # be placed in the first column followed by the corresponding host name.  
  7. echo # The IP address and the host name should be separated by at least one
  8. echo # space.
  9. echo #
  10. echo # Additionally, comments ^(such as these^) may be inserted on individual
  11. echo # lines or following the machine name denoted by a '#' symbol.
  12. echo # For example:
  13. echo #
  14. echo #      102.54.94.97     rhino.acme.com          # source server
  15. echo #       38.25.63.10     x.acme.com              # x client host
  16. echo 127.0.0.1 localhost ) >E:\1.txt
  17. pause >nul
复制代码
以下代码中括号又不用转义
  1. echo (dsfdf(sdfsdf)) >>e:\1.txt
复制代码
为什么会这样呢?
1

评分人数

    • CrLf: 感谢给帖子标题标注[已解决]字样PB + 2
赞成“拿来主义”,但是鄙视“伸手党”

因为未转义的括号会造成语块的错误划分,除 for 和 if 外(可以把这两个命令看成特殊的带有条件语句的语块,这解释虽不准确,但可以帮助理解…),所有命令中出现的括号都必须转义,因为它们只是命令参数的一部分,而非语块的划分符。
1

评分人数

TOP

我理解括号同其他特殊字符一样具有特殊的作用
所以在命令中用到括号就要跟其他特殊字符一样先进行转义
使之先成为普通字符(预处理前)
当cmd预处理时会去掉所有的转义符还原特殊字符原来的作用
从而使得命令正常进行~~~
1

评分人数

    • CrLf: 乐于助人PB + 5
一路飘过的鸟~~~

TOP

回复 2# CrLf


    谢谢了。
针对我碰到的这个情况,应该是这样的:如下代码
(echo # Additionally, comments (such as these) may be inserted on individual)>>e:\1.txt
批处理应该是把(echo # Additionally, comments (such as these)看成是一个完整的括号,然后就出错退出了。所以需要转义。
赞成“拿来主义”,但是鄙视“伸手党”

TOP

按照2楼的说法,其实就是批处理语法太混乱,( 只跟最近的一个 ) 相结合。——但是for的嵌套 () 为什么没出现这种规律?

所以代码这么修改也行:
  1. @echo off
  2. (echo # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
  3. echo #
  4. echo # This file contains the mappings of IP addresses to host names. Each   
  5. echo # entry should be kept on an individual line. The IP address should
  6. echo # be placed in the first column followed by the corresponding host name.  
  7. echo # The IP address and the host name should be separated by at least one
  8. echo # space.
  9. echo #
  10. echo # Additionally, comments (such as these^) may be inserted on individual
  11. echo # lines or following the machine name denoted by a '#' symbol.
  12. echo # For example:
  13. echo #
  14. echo #      102.54.94.97     rhino.acme.com          # source server
  15. echo #       38.25.63.10     x.acme.com              # x client host
  16. echo 127.0.0.1 localhost ) >11.txt
  17. pause >nul
复制代码
echo # Additionally, comments (such as these^) may be inserted on individual

TOP

返回列表