A problem like this gets around an order or magnitude easier to solve if you don't use regular expressions.
package require fileutil
::fileutil::foreachLine line somefile.txt {
if {[lindex $line end] == 1} {
puts $line
}
}
This solution looks at each line in the file and checks if the last item is equal to 1. If so, the line is printed.
You could also count them / sum them:
set count 0
set sum 0
::fileutil::foreachLine line somefile.txt {
if {[lindex $line end] == 1} {
puts $line
incr count
incr sum [lindex $line end] ;# yeah, I know, always 1
}
}
puts "Number of lines: $count"
puts "Sum of items: $sum"
If fileutil isn't available in your Tcl installation and you can't or don't want to install it, you can use the lower-level core equivalent:
set f [open somefile.txt]
while {[gets $f line] >= 0} {
if {[lindex $line end] == 1} {
puts $line
}
}
close $f
If you absolutely must use a regular expression, in this case you could do this:
::fileutil::foreachLine line somefile.txt {
if {[regexp {\m1$} $line]} {
puts $line
}
}
This regular expression finds lines that end with the digit 1 in a word by itself (i.e. there are no digits or word characters preceding it).
Documentation: close, fileutil package, gets, if, lindex, open, package, puts, Syntax of Tcl regular expressions, regexp, while