Search code examples
listtclregsub

Remove elements with dot extension from list using regex or string matching


I'm newbie to Tcl. I have a list like this:

set list1 {
    dir1
    fil.txt
    dir2
    file.xls
    arun
    baskar.tcl
    perl.pl
}

From that list I want only elements like:

dir1
dir2
arun

I have tried the regexp and lsearch but no luck.

Method 1:

set idx [lsearch $mylist "."]

set mylist [lreplace $mylist $idx $idx]

Method 2:

set b [regsub -all -line {\.} $mylist "" lines]

Solution

  • Method 1 would work if you did it properly. lsearch returns a single result by default and the search criteria accepts a glob pattern. Using . will only look for an element equal to .. Then you'll need a loop for the lreplace:

    set idx [lsearch -all $list1 "*.*"]
    foreach id [lsort -decreasing $idx] {
        set list1 [lreplace $list1 $id $id]
    }
    

    Sorting in descending order is important because the index of the elements will change as you remove elements (also notice you used the wrong variable name in your code snippets).


    Method 2 would also work if you used the right regex:

    set b [regsub -all -line {.*\..*} $list1 ""]
    

    But in that case, you'd probably want to trim the results. .* will match any characters except newline.


    I would probably use lsearch like this, which avoids the need to replace:

    set mylist [lsearch -all -inline -not $list1 "*.*"]