TCL regsub replace last / in file name

1.6k Views Asked by At

To replace the last /in a file name with : I tried following code.

set x a/b/c
regsub {.*(\/)\S+$} $x {:}

The undesired result is :.

The desired result is a/b:c

Examples:

a -> a
a/b -> a:b
aa/b -> aa:b
aa/bb/.../dd/e -> aa/bb/.../dd:e

Feedback is appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

With a regular expression, you can say

set new [regsub {/([^/]+)$} $x {:\1}]       ;# ==> a/b:c

foreach d {a a/b aa/b aa/bb/.../dd/e} {puts "$d => [regsub {/([^/]+)$} $d {:\1}]"}
# a => a
# a/b => a:b
# aa/b => aa:b
# aa/bb/.../dd/e => aa/bb/.../dd:e

Or, use the file command

set new [file dirname $x]:[file tail $x]    ;# ==> a/b:c

The problem with the 2nd option is if the string does not contain a slash, you get a => .:a so you need to do something like this:

foreach d {a a/b aa/b aa/bb/.../dd/e} {
    set new [expr {[string first / $d] == -1 ? $d : "[file dirname $d]:[file tail $d]"}]
    puts "$d -> $new"
}