Reputation: 125
If I have a variable that has values like this:
set var "/abc/def/ghi/jkl/mno/pqr"
How do I use regsub so that it removes everything except the second last value "mno"?
Upvotes: 1
Views: 567
Reputation: 137587
Well, you can do this:
set updatedValue [regsub {^.*(mno).*$} $value {\1}]
which is an old trick from the Unix utility, sed, translated into Tcl. That will remove everything but the last text to match mno
. Pick your RE appropriately.
And don't use this for manipulating filenames, please. It might work, but it makes your code more confusing. The file
command has utility subcommands for this sort of work and they handle tricky gotchas that you might not be aware of.
Upvotes: 1
Reputation: 1482
Try this, Using split
and lindex
% set var "/abc/def/ghi/jkl/mno/pqr"
/abc/def/ghi/jkl/mno/pqr
%
% puts "[lindex [split $var "/"] end-1]"
mno
Upvotes: 1
Reputation: 5723
Why a regular expression? How about:
set val [file tail [file dirname $var]]
References: file
Upvotes: 1