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=%
2
  • Take a look at this: stackoverflow.com/questions/3216475/… Commented Aug 12, 2012 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 Commented Aug 12, 2012 at 18:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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%

2 Comments

exactly what I needed but dam! any way to make it simpler?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.