Remove first part of the string by batch command

1.5k views Asked by At

This is my full path U:\temp\Obj\x64\Debug\XUIBaseHelp\XUIBaseHelp.def

I need to get the \x64\Debug\XUIBaseHelp\XUIBaseHelp.def part from this by removing first part.

Any idea?

2

There are 2 answers

1
Anders Lindahl On

If it is always U:\temp\Obj that needs to be removed, a simple string edit/replace will do:

C:\>set FOO=U:\temp\Obj\x64\Debug\XUIBaseHelp\XUIBaseHelp.def
C:\>set BAR=%FOO:U:\temp\Obj=%
C:\>echo %BAR%
\x64\Debug\XUIBaseHelp\XUIBaseHelp.def
2
MC ND On

There are several ways to do it depending on what the final requirements are. While the result will be the same, it is not the same to remove two folders from the start than to search three folders up. Some samples

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "value=U:\temp\Obj\x64\Debug\XUIBaseHelp\XUIBaseHelp.def"

    rem Tokenize and remove elements from the start
    set "newValue="
    for /f "tokens=3,* delims=\:" %%a in ("%value%") do set "newValue=\%%b"
    echo %newValue%

    rem Going backward from the end
    set "newValue="    
    for %%a in ("%value%\..\..\..\..") do set "newValue=%%~fa"
    setlocal enabledelayedexpansion & for /f "delims=" %%a in ("!value:%newValue%=!") do (endlocal & set "newValue=%%a")
    echo %newValue%

    rem Discarding known elements at the start
    set "newValue=\x64%value:*x64=%"
    echo %newValue%

    set "newValue=%value:*\Obj\=\%"
    echo %newValue%