2

How can I remove // remove absolute path string from fullPath string

set abs_p=C:\abspath\
set rel_p=C:\abspath\foo\boo\bar

How can I remove the abs_p from the rel_p? I'm not getting the syntax working

set rel_p=%rel_p:abs_p=%
user391986
  • 29,536
  • 39
  • 126
  • 205
  • Take a look at this: http://stackoverflow.com/questions/3216475/batch-remove-a-string-from-a-string – Aleksander Azizi Aug 12 '12 at 18:32
  • thanks but my problem is the string to replace is a variable and I'm not seeing how to specify a variable inside this command, it escapes the command – user391986 Aug 12 '12 at 18:37

2 Answers2

5

A quick and dirty solution that works as long as abs_p does not contain = or !

@echo off
setlocal enableDelayedExpansion

set "abs_p=C:\abspath\"
set "rel_p=C:\abspath\foo\boo\bar"

set "rel_p=!rel_p:*%abs_p%=!"
echo relative path = !rel_p!

A quick solution that should work always.

@echo off
setlocal enableDelayedExpansion

set "abs_p=C:\abspath\"
set "rel_p=C:\abspath\foo\boo\bar"

>temp.txt echo !abs_p!
for %%N in (temp.txt) do set /a len=%%~zN-2
set "rel_p=!rel_p:~%len%!"
del temp.txt

echo relative path = !rel_p!

The above uses a crude but effective method to get the string length of the absolute path. There is a more complex but screaming fast strLen function that can be used instead.

dbenham
  • 127,446
  • 28
  • 251
  • 390
4

For your sample input this script produces

foo\boo\bar

set abs_p=C:\abspath\
set rel_p=C:\abspath\foo\boo\bar

set newp=
set rec_a=
set rec_r=

call :strip  %rel_p%\ %abs_p%
goto :END

:strip
set rec_a_part=
set rec_a=
set rec_r_part=
set rec_r=

for /F "tokens=1,* delims=\" %%t  in ("%2") do (
    set rec_a_part=%%t
    set rec_a=%%u
 )
for /F "tokens=1,* delims=\" %%t  in ("%1") do ( 
  set rec_r_part=%%t
  set rec_r=%%u
)
if not !%newp%!==!! set newp=%newp%\
if not !%rec_a_part%!==!%rec_r_part%! set newp=%newp%%rec_r_part%
if not !%rec_r%!==!! call :strip  %rec_r% %rec_a%
goto :EOF

:END
echo %newp%
rene
  • 41,474
  • 78
  • 114
  • 152
  • exactly what I needed but dam! any way to make it simpler? – user391986 Aug 12 '12 at 20:08
  • Simpler? Yes, use vbscript, or wscipt or powershell, in other words: a decent programming language. If it fits your need don't forget to mark my answer as correct as well for the answers for on other questions you have asked. – rene Aug 12 '12 at 20:28