James
James

Reputation: 125

How to use regsub to grab values after a pattern tcl?

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

Answers (4)

Donal Fellows
Donal Fellows

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

toxic_boi_8041
toxic_boi_8041

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

glenn jackman
glenn jackman

Reputation: 246827

% regexp {.*/([^/]+)/} $var -> val
1
% set val
mno

Upvotes: 1

Brad Lanam
Brad Lanam

Reputation: 5723

Why a regular expression? How about:

set val [file tail [file dirname $var]]

References: file

Upvotes: 1

Related Questions