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.
Most importantly, all your polite critiques, elaborations, and corrections are heartily welcomed.
How to kill lines before and after a pattern
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)
}
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 $
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 $
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.
Total Comments 0