0

我已经在 tcl 中解析了一个文件,我读到了这样的行:

while {[gets $thefile line] >= 0} { ...

我像那样搜索我的模式

   if { [regexp {pattern} $line] } { ...

我想将第 n+2 行存储在一个变量中,我该怎么做(我不能尝试在下一行中找到一个模式,因为它总是在变化)?

非常感谢

4

2 回答 2

1

最简单的方法是getsif正文中添加一个额外的内容:

while {[gets $thefile line] >= 0} {
    # ...
    if { [regexp {pattern} $line] } {
        if {[gets $thefile secondline] < 0} break
        # Now $line is the first line, and $secondline is the one after
    }
    # ...
}
于 2012-06-21T14:48:30.623 回答
0

您可以在运行时将模式空间构建为列表。例如:

set lines {}
set file [open /tmp/foo]
while { [gets $file line] >=0 } {
    if { [llength $lines] >= 3 } {
        set lines [lrange $lines 1 2]
    }
    lappend lines $line
    if { [llength $lines] >= 3 } {
        puts [join $lines]
    }
}

第三次通过循环后,行将始终包含最近的三个行在我的示例中,输出如下所示:

line 1 line 2 line 3
line 2 line 3 line 4
line 3 line 4 line 5
line 4 line 5 line 6
line 5 line 6 line 7
line 6 line 7 line 8
line 7 line 8 line 9

然后,您可以使用正则表达式搜索循环内的行。

于 2012-06-21T14:53:35.440 回答