How do I escape Ampersand (&) from current working directory %~dp0 in batch file

依然范特西╮ 提交于 2020-01-30 09:35:06

问题


I usually get the current working directory by giving the batch command %~dp0 for combine multiple csv files. But I encountered ampersand (&) symbol while getting current working directories which makes batch file broke after the '&' saying the path after & is not recognized as an internal or external command.

Can any of you guys please help me in modifying my below script in identifying & and replacing it with ^& (as this can escape the & and run the batch file). Any of your suggestions is appreciated;

Here is my code:

@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

回答1:


Putting quotation marks around %~dp0 should be enough:

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

Btw, I don't understand why you use pushd. You don't popd anywhere in your code so pushd seems useless. If I understand ECHO Set working directory correctly, you should replace pushd with CD %~dp0.



来源:https://stackoverflow.com/questions/42977344/how-do-i-escape-ampersand-from-current-working-directory-dp0-in-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!