0

I need to get the relative filepath of files with bat.

The folder structure

file.bat
- folder1
-- subfolder1
----- abc.image
----- def.image
-- subfolder2
---- more.image
- folder2
-- subfolder1
---- alsoimages.image
-- subfolder2

For abc.image, I'd like to get the name of the folder (here e.g. folder1) and the combination folder+subfolder (here e.g. folder1/subfolder1)

I looked at this post: batch programming - get relative path of file but I cant make it work for me. The output keeps giving me too many hierachies.

What I want to do ultimately is this:

set "prefix=td"
set "file=list_of_images.xml"

echo ^<?xml version="1.0"  encoding="UTF-8" standalone="yes"?^> > %file%
echo ^<files^> >>  %file%

    for /r %%x in (*.image) do ( 

        echo ^<file folder="(here e.g. folder1)" subfolder="(here e.g. folder1/subfolder1)" id="%prefix%%%~nx" type="image" /^> >>  %file%
    )

echo  ^</files^> >>  %file%

Thanks for help and tips!

Community
  • 1
  • 1
user3813234
  • 1,580
  • 1
  • 29
  • 44

2 Answers2

1

One of next code snippets could help:

  for /r %%x in (*.image) do (
      for /F "tokens=1* delims=\" %%G in ("%%~px") do (

        echo "%%~G" "%%~H" "%prefix%%%~nx"

      ) 
  )

Splitting to more than one subfolders:

  for /r %%x in (*.image) do (
      for /F "tokens=1,2* delims=\" %%G in ("%%~px") do (

        echo "%%~G" "%%~H" %%~I "%prefix%%%~nx"

      ) 
  )

And so on...

JosefZ
  • 28,460
  • 5
  • 44
  • 83
1
for /f "tokens=1,* delims=\" %%a in ('
    xcopy ".\*.image" "%temp%" /s /e /l 
') do if not "%%b"=="" echo(%%b

The easiest way to get a list of files with relative paths is to use an xcopy command to generate the list (/l) of files.

You can also use a subst command to create a "virtual" drive letter with the root of the drive pointing to the required starting folder and then use your same code referencing this drive, that now will not retrieve the upper folder structure

edited to adapt to comments

for /f "tokens=2-4 delims=\" %%a in ('
    xcopy ".\*.image" "%temp%" /s /e /l 
') do echo folder=%%a subfolder=%%b file=%%c

The output from xcopy command is in the format

.\folder\subfolder\file

so, using backslash as delimiter we skip the first token and retrieve the second (folder), third (subfolder) and fourth (file)

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Okay, this one works really well. But how do I get the substrings from folder/folder1/abc.image so that I have "folder1" and "folder1/subfolder1"? – user3813234 Mar 17 '15 at 15:36