【问题标题】:How do I escape Ampersand (&) from current working directory %~dp0 in batch file如何从批处理文件中的当前工作目录 %~dp0 中转义与号(&)
【发布时间】:2017-08-16 02:01:02
【问题描述】:

我通常通过给出批处理命令 %~dp0 来获取当前工作目录以合并多个 csv 文件。 但是我在获取当前工作目录时遇到了 & 符号,这使得批处理文件在 '&' 表示 & 之后的路径不被识别为内部或外部命令之后中断。

请你们中的任何人帮助我修改我的以下脚本以识别 & 并用 ^& 替换它(因为这可以转义 & 并运行批处理文件)。感谢您提出任何建议;

这是我的代码:

@echo off

ECHO Set working directory
pushd %~dp0             - How to escape & in this line???

ECHO Deleting existing combined file
del combined.csv

setlocal ENABLEDELAYEDEXPANSION

REM set count to 1
set cnt=1

REM for each file that matches *.csv

for %%i in (*.csv) do (

REM if count is 1 it's the first time running

  if !cnt!==1 (

REM push the entire file complete with header into combined.csv - this will also create combined.csv

for /f "delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv

REM otherwise, make sure we're not working with the combined file and
  ) else if %%i NEQ combined.csv (

REM push the file without the header into combined.csv
    for /f "skip=1 delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
  )

REM increment count by 1
  set /a cnt+=1
)

cmd \k

【问题讨论】:

    标签: batch-file special-characters


    【解决方案1】:

    %~dp0 周围加上引号就足够了:

    ...
    pushd "%~dp0"
    ...
    

    顺便说一句,我不明白你为什么使用pushd。你在代码中的任何地方都没有popd,所以pushd 似乎没用。如果我对ECHO Set working directory 的理解正确,您应该将pushd 替换为CD %~dp0

    【讨论】:

    • 非常感谢 Michael 的建议,现在我可以逃脱 '&'
    • @NarendraPamuru 如果这对您有帮助,您应该通过单击旁边的灰色复选标记将其标记为已接受的答案。
    • 如果您使用 CD 而不是 PUSHD,那么您应该包括 \D 选项。
    猜你喜欢
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2013-06-08
    • 2011-05-24
    相关资源
    最近更新 更多