tongtong
tongtong

Reputation: 47

TCL How to remove part of the filename

All the filename is about AA/BB/CC/N*/DD/EE but I need is only N1,N2,N3

How can I remove AA/BB/CC/ and /DD/EE in TCL

set filename [file tail $name] ->is not available.

Thanks for help.

Upvotes: 0

Views: 574

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137557

Using file split and lindex is great if the element of interest is at a fixed index. If it isn't, lsearch comes into its own:

set filenames {AA/BB/CC/N1/DD/EE AA/BB/CC/N2/DD/EE AA/BB/CC/N3/DD/EE}

foreach name $filenames {
    set parts [file split $name]
    set part [lsearch -inline -glob $parts "N*"]
    puts $part
}

The -glob mode is actually default, but I think it helps to be specific as it reminds anyone reading the code that this is glob matching, not exact. (There's also -regexp for when you have a complicated pattern to match for an element.)

Upvotes: 0

Shawn
Shawn

Reputation: 52334

You can use file split PATH to split up the path into individual components, and lindex to get just the bit you want:

#!/usr/bin/env tclsh

set filenames {AA/BB/CC/N1/DD/EE AA/BB/CC/N2/DD/EE AA/BB/CC/N3/DD/EE}

foreach name $filenames {
    set parts [file split $name]
    puts [lindex $parts 3]
}

Upvotes: 1

Related Questions