Variable for getting absolute path in windows batch script

I have following script to list out all the files, recursively from a directory, having a .phtml extension.

@echo off
setlocal
for /f %%G in ('forfiles /s /m *.phtml /c "cmd /c echo @relpath"') do echo %%G >> listoffiles.txt
endlocal
exit

It lists out only relative path to files. The above script is running from an intermediate location, so I am not getting full paths in @relpath variable.

Also I am getting quotes in the result lines, which I want to remove.

I want to get absolute path to those files with a few code changes as possible, if a global-variable is available which can be used in my code then it's best for me, as I am not much of Windows batch scripter.


Solution 1:

I am not getting full paths in the @relpath variable.

also I am getting quotes in the result lines, which I want to remove.

The following batch file does what you want:

@echo off
setlocal enableDelayedExpansion
for /f %%G in ('forfiles /s /m *.phtml /c "cmd /c echo @path"') do (
  set _name=%%G
  rem strip the quotes
  echo !_name:~1,-1! >> listoffiles.txt
  )
endlocal
exit

Notes:

  • Uses @path (Full path of the file) instead of @relpath (Relative path of the file).
  • Uses a variable substring expression to remove the quotes (:~1,-1 removes the first and last characters from the variable string).
  • Uses setlocal EnableDelayedExpansion so that variables are updated correctly in the for loop.

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
  • for /f - Loop command against the results of another command.
  • forfiles - Select a file (or set of files) and execute a command on each file. Batch processing.
  • variables - Extract part of a variable (substring).