Escape special character in a windows batch

血红的双手。 提交于 2019-12-04 05:29:00

问题


I have a batch file that receive a path as first argument. The path is always composed with specials characters like ^,é or è.

The call is similar to this

D:\Script>MyBatch My\path\test_00170_LASTNAME^Firstname\image

There is always this error: unknown specified path

When I echo the first argument in my bash I can see (notice the missing ^)

My\path\test_00170_LASTNAMEFirstname\image

So I tried to escape this character by adding another ^ just before

My\path\test_00170_LASTNAME^^Firstname\image

But when I echo this one, I have the same result ...

My\path\test_00170_LASTNAMEFirstname\image

I also tried to put the ^ between quotes but this did not work


回答1:


You need to escape the caret signs at the command line or better put the path into quotes.

In both cases you should work with delayed expansion, as then the content will not be modified when it is expanded.

myBatch "C:\LASTNAME^Firstname\image"

or

myBatch C:\LASTNAME^^Firstname\image

And in your batch use swomething like this

@echo off
set "arg1=%~1"
setlocal EnableDelayedExpansion
echo !arg1!



回答2:


You need to escape it twice - once when you input the path as an argument to the batch script, and again when echo'ing it:

caret_input.bat:

echo %1

Double-escaped (notice how it's already escaped when the batch file starts outputting):

C:\>caret_input.bat my\path^^^^is\special

C:\>echo my\path^is\special
my\path^is\special

If you were to use a string with a special character inside the batch file, your method of escaping it just once would work just fine:

caret_escape.bat:

echo my\path^^is\special

and the output

C:\>echo my\path^is\special
my\path^is\special


来源:https://stackoverflow.com/questions/32817929/escape-special-character-in-a-windows-batch

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