Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印TCL中匹配regexp前后的行_Regex_File_Tcl - Fatal编程技术网

打印TCL中匹配regexp前后的行

打印TCL中匹配regexp前后的行,regex,file,tcl,Regex,File,Tcl,我希望能够打印10行之前和10行之后,我遇到一个匹配的模式在一个文件。我通过正则表达式匹配模式。我需要一个特定于TCL的解决方案。我基本上需要grep-b10-a10功能的等价物 提前谢谢 您想到的唯一机制是将输入数据拆分为一系列行。然后,您需要浏览列表,无论何时找到匹配项,都会从列表中输出一个合适的条目集合 据我所知,没有一种内置的、简单的方法可以做到这一点 tcllib中可能有一些有用的东西 我自己会使用grep。如果数据“相对较小”(在现代计算机上实际上可能是100MB或更大),那么您可以

我希望能够打印10行之前和10行之后,我遇到一个匹配的模式在一个文件。我通过正则表达式匹配模式。我需要一个特定于TCL的解决方案。我基本上需要grep-b10-a10功能的等价物


提前谢谢

您想到的唯一机制是将输入数据拆分为一系列行。然后,您需要浏览列表,无论何时找到匹配项,都会从列表中输出一个合适的条目集合

据我所知,没有一种内置的、简单的方法可以做到这一点

tcllib
中可能有一些有用的东西


我自己会使用
grep

如果数据“相对较小”(在现代计算机上实际上可能是100MB或更大),那么您可以将其全部加载到Tcl中并在那里进行处理

# Read in the data
set f [open "datafile.txt"]
set lines [split [read $f] "\n"]
close $f

# Find which lines match; adjust to taste
set matchLineNumbers [lsearch -all -regexp $lines $YourPatternHere]
# Note that the matches are already in order

# Handle overlapping ranges!
foreach n $matchLineNumbers {
    set from [expr {max(0, $n - 10)}]
    set to [expr {min($n + 10, [llength $lines] - 1)}]
    if {[info exists prev] && $from <= $prev} {
        lset ranges end $to
    } else {
        lappend ranges $from $to
    }
    set prev $to
}

# Print out the ranges
foreach {from to} $ranges {
    puts "=== $from - $to ==="
    puts [join [lrange $lines $from $to] "\n"]
}
#读入数据
设置f[打开“datafile.txt”]
设置行[拆分[读取$f]“\n”]
收盘价$f
#找出匹配的行;适应口味
设置匹配线编号[lsearch-all-regexp$lines$YourPatternHere]
#请注意,匹配项已按顺序排列
#处理重叠范围!
foreach n$matchlinenumber{
从[expr{max(0,$n-10)}设置
设置为[expr{min($n+10,[llength$行]-1}]

如果{[info exists prev]&&$from,我就不能真正使用grep或tcllib。不过,我不知道如何通过拆分输入数据来实现这一点。Donal下面更完整的回答显示了如何拆分行;如果您无法从丰富的细节中选择它,那么它就是
设置行[split[read$f]\n]
[read$f]
返回文件中的所有数据,然后
[split…\n]
将该数据转换为一个列表,其中输入数据中的换行符被删除并分隔列表项。祝你好运。我在设置MatchLineNumber[lsearch-all-regexp$lines$YourPatternHere]时遇到以下错误#args:应该是“lsearch?模式?列表模式”@junosman您一定在使用非常旧的Tcl版本。8.4中引入了
-all
选项…