Ignore percent sign in batch file

Viewed 39011

I have a batch file which moves files from one folder to another. The batch file is generated by another process.

Some of the files I need to move have the string "%20" in them:

move /y "\\myserver\myfolder\file%20name.txt" "\\myserver\otherfolder"

This fails as it tries to find a file with the name:

\\myserver\myfolder\file0name.txt

Is there any way to ignore %? I'm not able to alter the file generated to escape this, such as by doubling percent signs (%%), escaping with / or ^ (caret), etc.

6 Answers

How to "escape" inside a batch file withoput modify the file** The original question is about a generated file, that can't be modified, but contains lines like:

move /y "\\myserver\myfolder\file%20name.txt" "\\myserver\otherfolder"

That can be partly solved by calling the script with proper arguments (%1, %2, ...)

@echo off

set "per=%%"
call generated_file.bat %%per%%1 %%per%%2 %%per%%3 %%per%%4

This simply sets the arguments to:

arg1="%1"
arg2="%2"
...

How to add a literal percent sign on the command line

mklement0 describes the problem, that escaping the percent sign on the command line is tricky, and inside quotes it seems to be impossible.

But as always it can be solved with a little trick.

for %Q in ("%") do echo "file%~Q20name.txt"

%Q contains "%" and %~Q expands to only %, independent of quotes.

Or to avoid the %~ use

for /F %Q in ("%") do echo "file%Q20name.txt"

You should be able to use a caret (^) to escape a percent sign.

Editor's note: The link is dead now; either way: It is % itself that escapes %, but only in batch files, not at the command prompt; ^ never escapes %, but at the command prompt it can be used indirectly to prevent variable expansion, in unquoted strings only.

The reason %2 is disappearing is that the batch file is substituting the second argument passed in, and your seem to not have a second argument. One way to work around that would be to actually try foo.bat ^%1 ^%2... so that when a %2 is encountered in a command, it is actually substituted with a literal %2.

Related