Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch script replace variable string within string

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=%
like image 975
user391986 Avatar asked Sep 23 '26 23:09

user391986


2 Answers

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.

like image 149
dbenham Avatar answered Sep 26 '26 06:09

dbenham


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%
like image 25
rene Avatar answered Sep 26 '26 07:09

rene