Reputation:
I have two strings in variables where the left part of the string is always same. I need to get the rightmost part:
set cwd "/this/is/my/path"
set full_file "/this/is/my/path/test.tcl"
I need the following:
"/test.tcl"
Upvotes: 1
Views: 483
Reputation: 246754
I can think of two ways:
% set cwd "/this/is/my/path"
% set full_file "/this/is/my/path/test.tcl"
% string map [list $cwd ""] $full_file
/test.tcl
% string range $full_file [string length $cwd] end
/test.tcl
The 2nd one does not verify they are the same though.
And the 1st one does not specify to match at the start of the string.
Both of these caveats can be satisfied with:
if {[string match "${cwd}*" $full_file]} { ... }
Upvotes: 0
Reputation: 5723
Tcl has excellent path manipulation functions, they may be helpful:
set tail [file tail $full_file]
Note that this will not include the leading /.
If your path may contain other elements past the $cwd
, you can use
a regular expression to remove the prefix:
regsub $cwd $full_file {} tail
puts $tail
You have to be careful with this, if $cwd
contains any special
characters that the regular expression recognizes, it will fail
or get strange results. In which case you will need a procedure
to escape the special characters:
proc escapeRegex { val } {
regsub -all {([?*.+^${}()\\\[\]"])} $val {\\\1} val
return $val
}
regsub [escapeRegex $cwd] $full_file {} tail
puts $tail
( This code does not handle leading ~
characters ).
Upvotes: 1