2014-02-12 63 views

回答

0

想到的唯一機制就是讓您將輸入數據拆分爲行列表。然後,您需要掃描列表,並且每當您找到匹配項時,都會從列表中輸出合適的條目集合。

據我所知,沒有內置的,簡單的方法來做到這一點。

可能有些事在tcllib有用。我自己使用grep

+0

我真的不能使用grep或tcllib。我不知道如何通過分割輸入數據來解決它。 – junosman

+0

下面Donal的更全面的答案顯示瞭如何分割線條;如果你無法從豐富的細節中挑選它,那就是'設置行[split [read $ f] \ n]'。 '[read $ f]'返回文件中的所有數據,'[split ... \ n]'將數據轉換爲一個列表,其中輸入數據中的換行符被刪除並對列表條目進行分隔。祝你好運。 – nurdglaw

1

如果數據「相對較小」(在現代計算機上實際可能是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"] 
} 
+0

我在設置matchLineNumbers [lsearch -all -regexp $ lines $ YourPatternHere]時出現以下錯誤: 錯誤#參數:應該是「lsearch?mode?列表模式」 – junosman

+0

@junosman您必須使用Tcl的舊版本。 8.4中引入了-all選項... –

相關問題