3

This is the string I want to copy into clipboard:

mail from:<email@gmail.com>

I tried

echo mail from:^<email@gmail.com^> | clip

It gives me that "The syntax of the command is incorrect." but when I tried

echo mail from:^<email@gmail.com^> 

It shows the correct result. So I am wondering how should I modify the command?

OceanicSix
  • 177
  • 1
  • 5

2 Answers2

3

One solution is shown by @Magoo.
You need three carets, as first the complete line will be parsed and the carets escapes to the string:
echo mail from:^<email@gmail.com^> | clip
As the first caret escapes the second and the third escapes the redirection character.

Then the pipe creates two new instances of cmd.exe for both sides.
In both cmd.exe the partial commands are parsed a second time.

You need three carets as the batch parser parses the line two times.
(The space is only for better visualization)

echo ^^ ^< | clip
===>
echo ^ < | clip
===>
echo < | clip

The same with two carets would work completly different

echo ^^ < | clip
===>
failure as the < wouldn't be escaped and works as redirection

Another way
To avoid tripple carets you could also use percent variable expansion like

set "text=echo mail from:^<email@gmail.com^>"
echo %%text%% | clip

It's nearly the same effect, in the batch file the double percents are reduced to a single percent and in the pipe cmd instance the echo %text% will be expanded and then the single carets escapes the redirection characters

For more interessting samples you could look at
Why does delayed expansion fail when inside a piped block of code?

jeb
  • 78,592
  • 17
  • 171
  • 225
  • I am still confused about why we need to use the first caret to escape the second caret, what is the pointing in doing this? why shall we do this when using the pipe? – OceanicSix Feb 28 '18 at 02:21
  • @OceanicSix I added an example – jeb Feb 28 '18 at 08:02
2

Try:

echo mail from:^^^<email@gmail.com^^^> | clip
Magoo
  • 77,302
  • 8
  • 62
  • 84
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – rollstuhlfahrer Feb 27 '18 at 07:36
  • @rollstuhlfahrer: Certainly would. Wish I had a good explanation myself. Arrived at it purely empirically. Possibly jeb would have an explanation... – Magoo Feb 27 '18 at 08:23