The forfiles
command establishes several variables, indicated by a leading @
, which return data concerning the currently iterated item to the loop body.
All the variables related to the path and name of the iterated item return the value enclosed in ""
. Those are: @file
, @fname
, @ext
, @path
and @relpath
.
So: how can you get rid of the enclosing double-quotes?
For example, the following code returns relative paths to text files in the given root directory:
forfiles /P "C:\root" /M "*.txt" /C "cmd /C echo @relpath"
Assuming that C:\root
contains two files file1.txt
and file2.txt
, the output will be:
".\file1.txt"
".\file2.txt"
However, I want the list of files without the surrounding ""
.
I am working on Windows 7 64-bit.
One approach is to nest a
for %I
loop within theforfiles
and use the%~I
expansion -- use this code in a Command Prompt window:To use that code within a batch file you must double the
%
-signs:The returned list of files will be (relying on the sample files from the original question):
Another variant is to nest another
forfiles
in the body of the initial one, becauseforfiles
removes (non-escaped) double-quotes within given strings like the command line after/C
:Or alternatively (the doubled inner
forfiles
is intentional, this works around a bug -- see this post):The inner
forfiles
will enumerate exactly one item, which is the one passed over by the outer loop. Since@relpath
is already expanded when the inner loop is executed, the quotes are removed as they are not escaped.So the returned list of files looks like (again taking the sample files from the original question):
The additional line-break between the lines is generated by
forfiles
. You can avoid that using redirection (dismissforfiles
output, but display only theecho
output in the console window):I remove the quotes like this:
results: