junosman
junosman

Reputation: 1

Print lines before and after matching regexp in TCL

I want to be able to print 10 lines before and 10 lines after I come across a matching pattern in a file. I'm matching the pattern via regex. I would need a TCL specific solution. I basically need the equivalent of the grep -B 10 -A 10 feature.

Thanks in advance!

Upvotes: 0

Views: 3633

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

If the data is “relatively small” (which can actually be 100MB or more on modern computers) then you can load it all into Tcl and process it there.

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

Upvotes: 1

nurdglaw
nurdglaw

Reputation: 2117

The only mechanism that springs to mind is for you to split the input data into a list of lines. You'd then need to sweep through the list and whenever you found a match output a suitable collection of entries from the list.

To the best of my knowledge there's no built-in, easy way of doing this.

There might be something useful in tcllib.

I'd use grep myself.

Upvotes: 0

Related Questions