user5159376
user5159376

Reputation: 19

Delete all line before and after a pattern is found in tcl

I would like to delete all line before and after, when a pattern is found in an auto generated file named "Summary.txt". 1) Delete all line before the expression "Summary of Result" is found. 2) Delete all line after the expression "End of Result" is found.

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX Here are some unwanted lines XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Summary of Result
Line 2: Grammar error
Line 14: Missing of punctuations "!"
Line 15: Spelling error
Line 21: Spelling error
Line 40: Missing of punctuations ","

End of Result
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX Here are some unwanted lines XXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

I am new in TCL. Need some help over here. Thank you very much.

Upvotes: 0

Views: 376

Answers (2)

glenn jackman
glenn jackman

Reputation: 247210

A more line-oriented alternative

set fid [open Summary.text]
set in_result false
while {[gets $fid line] != -1} {
    if {[string match "*Summary of Result*" $line]} {set in_result true}
    if {$in_result} {puts $line}
    if {[string match "*End of Result*" $line]} break
}
close $fid

Upvotes: 1

Tim Tomkinson
Tim Tomkinson

Reputation: 21

This uses "fileutil" (from Tcllib) to read and write the files and "regexp" to extract the desired text:

package require fileutil
set data [::fileutil::cat Summary.txt]
if {![regexp "Summary of Result.*End of Result\n" $data result]} {
    error "Expression not found."
}
::fileutil::writeFile Output.txt $result

Upvotes: 2

Related Questions