Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching in Tcl

Tags:

regex

tcl

I have somefile.txt, contains lines like:

{ abc1 } 1
{ cde1 } 101
{ fgh1 } 1
{ ijk1 } 2 

its a huge file, i wanted to find only 1st and 3rd line and count them.

I have tried with regexp and lsearch(converting it to list) by {\s\}\s1\n} but its not working. What should I do...?

I have also tried {\s\}\s1} but it prints all 4 lines.

like image 433
ShivankG Avatar asked Jan 29 '26 22:01

ShivankG


1 Answers

Solution 1: If you dont want to use regexp and your inputs line have same format like {string} number

set fd [open "somefile.txt" r]
while {[gets $fd line] >= 0} {
    if {[lindex $line 1] == 1} {
        puts [lindex $line 1] ;# Prints only 1
        puts $line            ;# Prints Whole Line which has 1 at end
    }
}

Solution 2: If you want to use regexp, then go for group-capturing which is (.*)

set fd [open "somefile.txt" r]
while {[gets $fd line] >= 0} {
    if {[regexp "\{.*\} (.*)" $line match match1]} {
        if {$match1 == 1} {
            puts $line
        }
    }
}

Solution 3: Based on @Peter suggestion on regexp

set fd [open "somefile.txt" r]
while {[gets $fd line] >= 0} {
    if {[regexp {\d+$} $line match]} {
        if {$match == 1} {
            puts $match ;# Prints only 1
            puts $line  ;# Prints whole line which has 1 at end 
        }
    }
}
like image 62
mf_starboi_8041 Avatar answered Feb 03 '26 01:02

mf_starboi_8041



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!