Search code examples
windowsbatch-filevariablescmdcontextmenu

Is there a way to extract/replace just the last folder in the windows batch file path variable %1? trying to use it as part of the file name


Seems a good place as any to ask

So I want to assign a file name being processed by a batch file to: LASTFOLDERIN%1PATHNAME-FOLDERNAME.rar using the %1 Windows sends me from the context menu.

So far I'm able to ALMOST make it, I get so far as:

WinRAR.exe a -r -ep1 -u -m0 -y "C:\Sorting\ %~p1-%~n1.rar" "%~1\*.*"

Which returns:

\FULL(DIR1\DIR2\DIR3)PATH\-FOLDERNAME.RAR

But the problem is I get the FULL path (multiple directories), not just the very last one, also, I get the \ that breaks the whole thing.

Question is, is there a way to extract just the last folder in the path variable %~1 that I get from the windows context menu argument?

Or if not, can I somehow replace the \ with - so I can rename the files manually later? to get something like this: -DIR1-DIR2-DIR3-FOLDERNAME.RAR

Any help would be greatly appreciated, I'm stuck here.

PS I'm sending %V to the batch file, since %1 did all kinds of weird things.


Solution

  • In your comment you asked: "Now if anyone knows how to get the last 2 directory variables instead of just the last one... it would be awesome haha."

    My answer was: "Simple: after set "PATHNAME=%1" use set "last1=%PATHNAME:\=" & set "last2=!last1!" & set "last1=%" & set "lastTwo=!last2!\!last1!" The result is in %lastTwo%"

    I think this is fairly simple code (just two lines). Anyway, here it is such a code, with the mod required to also get the third-to-last directory:

    @echo off
    setlocal EnableDelayedExpansion
    
    set "PATHNAME=%1"
    
    set "last1=%PATHNAME:\=" & set "last3=!last2!" & set "last2=!last1!" & set "last1=%"
    
    echo Full path name:   %PATHNAME%
    echo Last dir only:    %last1%
    echo From 2nd to last: %last2%\%last1%
    echo From 3rd to last: %last3%\%last2%\%last1%
    

    Output example:

    Full path name:   DIR1\DIR2\DIR3\DIR4\DIR5
    Last dir only:    DIR5
    From 2nd to last: DIR4\DIR5
    From 3rd to last: DIR3\DIR4\DIR5