Suraj Menon
Suraj Menon

Reputation: 49

Extract part of a path in batch script

I have a batch script with input say /home/home1/home2/home3/

I need to extract part of the file path say /home2/home3. How can I achieve this?

Thanks for the help!

Upvotes: 0

Views: 306

Answers (2)

Rob Biggs
Rob Biggs

Reputation: 21

for /f "tokens=1-4 delims=/" %%a in ('echo /home/home1/home2/home3/') do @echo /%%b/%%c

tokens tells for how many variables to spit out & delims tells it what to split on. %%a is the first token, it will count out a through d because it is told to generate 4.

you will likely have your path as a variable, you can just put it in place of the path in the example, but you may need to use delayed expansion

Upvotes: 0

npocmaka
npocmaka

Reputation: 57252

Not tested:

@echo off

set "p=/home/home1/home2/home3/"
set "p=%p:/=";"%"

setlocal ENABLEDELAYEDEXPANSION
for %%a in ("%p%") do (
    if "%%~a" neq "" set "butlast=!last!"
    if "%%~a" neq "" set "last=%%~a"

)

echo %butlast%/%last%

Upvotes: 1

Related Questions