how to trim the absolute directory path?

183 Views Asked by At

I have a absolute path to directory halo: /pkg/check/power/halo

I want to trim the absolute path to only: /pkg/halo

how can i do that using regex or pcreCompile function or unix?

2

There are 2 best solutions below

3
Fravadona On

With tcl:

set path "/pkg/check/power/halo"
set path [ split $path / ]
set path /[lindex $path 1]/[lindex $path end]
1
Donal Fellows On

When working with paths, you're strongly recommended to use file split and file join as they handle weirdnesses you're not aware of.

set path /pkg/check/power/halo
set pieces [file split $path]
set result [file join {*}[lrange $pieces 0 1] [lindex $pieces end]]

Or (removing pieces rather than selecting them):

set result [file join {*}[lreplace $pieces 2 end-1]]