#!/usr/bin/perl # # Grep for something and display the line and # the N lines following the match (default 1) # Prefix each line with the filename # if there is more than 1 file argument # Exit status: # 0 - a match was found # 1 - No match was found # >1 - An error was encountered (even if a match was found) use Getopt::Std; $usage_str = <<EOT; Usage: ngrep [-h] [-i] [-n #] [-q] pattern file1 file2 ... -h - Suppress file names when multiple file arguments are supplied -i - Do case-insensitive search -n - Number of lines to display after match (default: 1) -q - Treat pattern as a literal string instead of a regex -r - Don't reset count if line following matched line matches EOT getopts('qrhin:') or die $usage_str; die $usage_str unless @ARGV; $pttrn = shift; $pttrn = quotemeta $pttrn if $opt_q; $pttrn = '(?i)' . $pttrn if $opt_i; $pttrn = eval { qr/$pttrn/ } or die "$@$usage_str"; $n = length($opt_n) ? int($opt_n)+1 : 2; $filename = (@ARGV > 1 and ! $opt_h) ? sub { "$ARGV: " } : sub { '' }; $SIG{__WARN__} = sub { warn $_[0]; $error = 2 }; $status = 1; $i=0; while (<>) { ($status, $i) = (0, $n) if ! ($opt_r and $i) and /$pttrn/; $i--, print &$filename, $_ if $i; $i = 0 if eof; } exit($error || $status);
In reply to Grep - print matched line and next N lines by runrig
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |