Search code examples
windowsbatch-fileechotext-formatting

How do I get a relative path out of a windows batch file using echo?


How do I get relative directories / partial paths to display as echo output from a windows .bat file?

How to split the filename from a full path in batch?

Talks about everything but.

I've found drive letters, filenames, extensions, shortened (8.3) names, and full paths - but no relative paths.

I'm running a recursive FOR /R loop; which traverses sub-directories. I would like something - that doesn't have twenty characters of useless path info - that tells me which directory each duplicate file lives in... without hardcoding the .bat file to live in a certain directory/path?

Maybe a solution would be to measure the length of the script's path and cut that off of the front of the full path? But I don't know how to manipulate that.

Script could be in many locations:

F:\a.bat<BR>
F:\Dir1\fileA.txt<BR>
F:\Dir20\fileA.txt

C:\Users\Longusername\Desktop\Container\a.bat<BR>
C:\Users\Longusername\Desktop\Container\Dir1\fileA<BR>
C:\Users\Longusername\Desktop\Container\Dir20\fileA

And right now the only options I have for output are (%%~nxG):

fileA.txt
fileA.txt

Which doesn't tell me which directory each file is in...or (%%~pnxG)

\Users\Longusername\Desktop\Container\Dir1\fileA.txt
\Users\Longusername\Desktop\Container\Dir20\fileA.txt

What I'd like, from any location:

\Dir1\fileA.txt
\Dir20\fileA.txt

Could be missing the leading \, but that's negligible. Other options than echo are permissible if they'll work on most window machines. They may lead to more questions, though - as I've figured out my other pieces with echo.


Solution

  • quite easy, if you think about it: just remove the current directory path (%cd%):

    @echo off 
    setlocal enabledelayedexpansion
    for /r %%a in (*.txt) do (
      set "x=%%a"
      echo with \:    !x:%cd%\=\!
      echo without \: !x:%cd%\=!
    )
    

    By the way: \folder\file always refers to the root of the drive (x:\folder\file), so it's not exactly a relative path.