Escaping %’s in file-/folder-names at the command-line

Posted by Synetech on Super User See other posts from Super User or by Synetech
Published on 2012-04-07T02:17:36Z Indexed on 2012/04/07 5:34 UTC
Read the original article Hit count: 151

Does anybody of a way to access files and directories that have a % in their name (which is valid) from the command-line? Specifically, if there are two %’s and the text between them happens to correspond to an environment variable.

For example, if there is a file called C:\blah\%temp%.txt or a folder called C:\Program Files\%temp%\, none of the following will work because the variable gets expanded:

> dir "c:\blah\%temp%.txt"
> dir "c:\blah\^%temp^%.txt"
> dir "c:\blah\%%temp%%.txt"
> dir "c:\blah\\%temp\%.txt"

> dir "c:\program files\%temp%"
> dir "c:\program files\^%temp^%"
> dir "c:\program files\%%temp%%"
> dir "c:\program files\\%temp\%"


Using wildcards will work, but does not uniquely select the file/folder and may include others:

> dir "c:\blah\?temp?.txt"        (also shows ztempz.temp, 1tempa.txt, etc.)
> dir "c:\program files\?temp?"   (likewise)



(This is frustrating because every now and then—usually when Explorer is restarted for whatever reason—the environment variables stop expanding and some places where they are used end up creating files or directories with the environment variable in it. For example, because I configured Chromium to store its cache in a subdirectory of %temp%, if the variable expands, it is fine, but when it doesn’t, Chromium creates a directory called %temp% under its own directory and stores the cache—which can get large—there. I want to add a line to my temp-/junk-file cleaning script to automatically delete that folder if it exists, but I cannot figure out how to access it from the command-line without resorting to wildcards.)

© Super User or respective owner

Related posts about Windows

Related posts about command-line