首页 > 解决方案 > Tcl如何对文本中的某些单词进行排序并取最后一个

问题描述

我有一个文本并包含

#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

如何对所有#AA_VERSION =开头进行排序并打印最后一个?如果文本没有#开头,如何显示空格或没有版本。

感谢您的热心帮助!

标签: tcl

解决方案


假设您已经获得了行内容的列表,您需要做的是遍历该列表并测试有问题的行是否与您的标准匹配;如果是,则将匹配的信息存储在变量中。在循环结束时,变量将包含最后匹配的此类信息。

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"
}

获取文件中所有行列表的经典方法是以下过程:

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

set lines [linesOf "mydata.txt"]

推荐阅读