tongtong
tongtong

Reputation: 47

Tcl How to sort certain words in the text and take the last one

I have a text and contains

#AA_VERSION = Aa/10.10-d87_1
#AA_VERSION = Aa/10.10-d887_1
#AA_VERSION = Aa/10.10-d138_1
#AA_VERSION = Aa/10.10-d82_1

How can I sort all the #AA_VERSION = beginning and print the last one? And if the text don't have the # beginning ,how to show space or don't have version.

Thanks for your kindly help !!

Upvotes: 0

Views: 105

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137587

Assuming you've already got a list of the contents of the lines, what you need to do is iterate over that list and test whether the line in question matches your critera; if it does, you store that matched information in a variable. At the end of the loop, the variable will contain the last such info that was matched.

set version ""
set current ""
foreach line $lines {
    if {[regexp {^(#?)AA_VERSION *= *(.+)} $line -> commented info]} {
        if {$commented eq "#"} {
            set version [string trim $info]
        } else {
            if {$current ne ""} {
                puts stderr "WARNING: multiple current versions"
            }
            set current [string trim $info]
        }
    }
}

# All lines scanned; describe what we've found
if {$version eq ""} {
    puts "no #AA_VERSION line"
} else {
    puts "#AA_VERSION is $version"
}
if {$current eq ""} {
    puts "no current AA_VERSION"
} else {
    puts "current AA_VERSION is $current"
}

The classic way to get a list of all lines in a file is this procedure:

proc linesOf {filename} {
    set f [open $filename]
    set data [read $filename]
    close $f
    return [split $data "\n"]
}

set lines [linesOf "mydata.txt"]

Upvotes: 1

Related Questions