我希望能够在我遇到文件中的匹配模式之前打印10行和10行。我通过正则表达式匹配模式。我需要一个TCL特定的解决方案。我基本上需要相当于grep -B 10 -A 10功能。在TCL中匹配正则表达式之前和之后的打印行
在此先感谢!
我希望能够在我遇到文件中的匹配模式之前打印10行和10行。我通过正则表达式匹配模式。我需要一个TCL特定的解决方案。我基本上需要相当于grep -B 10 -A 10功能。在TCL中匹配正则表达式之前和之后的打印行
在此先感谢!
想到的唯一机制就是让您将输入数据拆分为行列表。然后,您需要扫描列表,并且每当您找到匹配项时,都会从列表中输出合适的条目集合。
据我所知,没有内置的,简单的方法来做到这一点。
可能有些事在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"]
}
我在设置matchLineNumbers [lsearch -all -regexp $ lines $ YourPatternHere]时出现以下错误: 错误#参数:应该是“lsearch?mode?列表模式” – junosman
@junosman您必须使用Tcl的旧版本。 8.4中引入了-all选项... –
我真的不能使用grep或tcllib。我不知道如何通过分割输入数据来解决它。 – junosman
下面Donal的更全面的答案显示了如何分割线条;如果你无法从丰富的细节中挑选它,那就是'设置行[split [read $ f] \ n]'。 '[read $ f]'返回文件中的所有数据,'[split ... \ n]'将数据转换为一个列表,其中输入数据中的换行符被删除并对列表条目进行分隔。祝你好运。 – nurdglaw