LinuxQuestions.org
Review your favorite Linux distribution.
Go Back   LinuxQuestions.org > Blogs > Here are some things which I hope will be helpful.
User Name
Password

Notices

Any code I post here should be considered experimental and unfinished. Don't use it in a production environment. It is your own responsibility to evaluate the code's fitness for any purpose. Programming isn't done in a vacuum, so be prepared to do your own research and teach yourself to do better.

Most importantly, all your polite critiques, elaborations, and corrections are heartily welcomed.
Rate this Entry

How to kill lines before and after a pattern

Posted 12-21-2011 at 05:45 PM by Telengard
Updated 12-21-2011 at 06:27 PM by Telengard
Tags awk

PHP Code:
#! /usr/bin/awk -f

# Deletes n lines before pattern and m lines after.
# Intended to be portable.
# It is your own responsibility to evaluate the fitness of this program.

BEGIN {
    
# set the following initializers as you please
    # FS=" "
    # OFS=" "
    
n=5
    m
=3
}

/
line 11/ { # insert your desired regex "pattern" between the slashes
    
pattern_line=FNR # No point in passing multiple files, but just in case.
    
filename=FILENAME # Is FILENAME portably available in END?
    
exit
}

END {
    while (
getline filename) {
    ++
line
    
if (line pattern_line n) print
    if (
line == pattern_line)    print # AWK has no ELIF construct? WTF?
    
if (line pattern_line m) print

    }
    
close(filename)

Here's the input file I fed it.

Code:
$ cat data.txt
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
line 12
line 13
line 14
line 15
line 16
line 17
line 18
line 19
line 20
$
Here's the output produced.

Code:
$ ./del-n-before-m-after.awk data.txt
line 1
line 2
line 3
line 4
line 5
line 11
line 15
line 16
line 17
line 18
line 19
line 20
$
My initial plan was to buffer lines before the pattern in an array, and then output them selectively according to the rule. That turned out to be far too complex.

This solution reads the file once to find the pattern, and a second time to print it. It should be just as fast, and require significantly less memory for enormous files. Bonus: it's a much simpler, and smaller program.
Posted in programming
Views 755 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 01:31 PM.

Main Menu

My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration