简体   繁体   中英

Escape Characters When Using Clip in Batch

The command that works on the command line is for /f "tokens=1* delims= " %A in ('nslookup myip.opendns.com. resolver1.opendns.com 2^>NUL^|find "Address:"') Do (echo %B)

In a batch that becomes for /f "tokens=1* delims= " %%A in ('nslookup myip.opendns.com. resolver1.opendns.com 2^>NUL^|find "Address:"') Do (echo %%B) which works

But to copy to clip board I need to do more with the escape character in the 2^>NUL^|. In batch the closest I've got it echo.for /f "tokens=1* delims= " %%A in ('nslookup myip.opendns.com. resolver1.opendns.com 2^^^>NUL^^^|find "Address:"') Do (echo %%B)|clip .

The output of which is for /f "tokens=1* delims= " %A in ('nslookup myip.opendns.com. resolver1.opendns.com 2>NUL|find "Address:"') Do (echo %B) which fails as 2>nul| is not escaped properly.

I tried adding a forth or even a fifth caret to 2>NUL|to try clip the output as 2^>nul^| but I can't figure it out. Is it possible?

Your command line is parsed several times, so you must use enough escaping in order to hide special characters from all of them:

echo for /F "tokens=1* delims= " %%A in ('nslookup myip.opendns.com. resolver1.opendns.com  2^^^^^^^> nul ^^^^^^^| find "Address:"'^) Do (echo(%%B^) | clip

At first the whole command line is parsed, which results in the following line:

 echo for /F "tokens=1* delims= " %%A in ('nslookup myip.opendns.com. resolver1.opendns.com 2^^^> nul ^^^| find "Address:"') Do (echo(%%B) | clip

Next each side of the pipe ( | ) is parsed again, so the left side results in this line:

 echo for /F "tokens=1* delims= " %%A in ('nslookup myip.opendns.com. resolver1.opendns.com 2^> nul ^| find "Address:"') Do (echo(%%B)

As you can see I also escaped the closing parentheses, so the code may also even be used within a parenthesised block of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM