| 1 |
# egrep.awk --- simulate egrep in awk |
| 2 |
# |
| 3 |
# Arnold Robbins, [email protected], Public Domain |
| 4 |
# May 1993 |
| 5 |
# Revised September 2020 |
| 6 |
|
| 7 |
# Options: |
| 8 |
# -c count of lines |
| 9 |
# -e argument is pattern |
| 10 |
# -i ignore case |
| 11 |
# -l print filenames only |
| 12 |
# -n add line number to output |
| 13 |
# -q quiet - use exit value |
| 14 |
# -s silent - don't print errors |
| 15 |
# -v invert test, success if no match |
| 16 |
# -x the entire line must match |
| 17 |
# |
| 18 |
# Requires getopt library function |
| 19 |
# Uses IGNORECASE, BEGINFILE and ENDFILE |
| 20 |
# Invoke using gawk -f egrep.awk -- options ... |
| 21 |
|
| 22 |
BEGIN { |
| 23 |
while ((c = getopt(ARGC, ARGV, "ce:ilnqsvx")) != -1) { |
| 24 |
if (c == "c") |
| 25 |
count_only++ |
| 26 |
else if (c == "e") |
| 27 |
pattern = Optarg |
| 28 |
else if (c == "i") |
| 29 |
IGNORECASE = 1 |
| 30 |
else if (c == "l") |
| 31 |
filenames_only++ |
| 32 |
else if (c == "n") |
| 33 |
line_numbers++ |
| 34 |
else if (c == "q") |
| 35 |
no_print++ |
| 36 |
else if (c == "s") |
| 37 |
no_errors++ |
| 38 |
else if (c == "v") |
| 39 |
invert++ |
| 40 |
else if (c == "x") |
| 41 |
full_line++ |
| 42 |
else |
| 43 |
usage() |
| 44 |
} |
| 45 |
if (pattern == "") |
| 46 |
pattern = ARGV[Optind++] |
| 47 |
|
| 48 |
if (pattern == "") |
| 49 |
usage() |
| 50 |
|
| 51 |
for (i = 1; i < Optind; i++) |
| 52 |
ARGV[i] = "" |
| 53 |
|
| 54 |
if (Optind >= ARGC) { |
| 55 |
ARGV[1] = "-" |
| 56 |
ARGC = 2 |
| 57 |
} else if (ARGC - Optind > 1) |
| 58 |
do_filenames++ |
| 59 |
} |
| 60 |
BEGINFILE { |
| 61 |
fcount = 0 |
| 62 |
if (ERRNO && no_errors) |
| 63 |
nextfile |
| 64 |
} |
| 65 |
ENDFILE { |
| 66 |
if (! no_print && count_only) { |
| 67 |
if (do_filenames) |
| 68 |
print file ":" fcount |
| 69 |
else |
| 70 |
print fcount |
| 71 |
} |
| 72 |
|
| 73 |
total += fcount |
| 74 |
} |
| 75 |
{ |
| 76 |
matches = match($0, pattern) |
| 77 |
if (matches && full_line && (RSTART != 1 || RLENGTH != length())) |
| 78 |
matches = 0 |
| 79 |
|
| 80 |
if (invert) |
| 81 |
matches = ! matches |
| 82 |
|
| 83 |
fcount += matches # 1 or 0 |
| 84 |
|
| 85 |
if (! matches) |
| 86 |
next |
| 87 |
|
| 88 |
if (! count_only) { |
| 89 |
if (no_print) |
| 90 |
nextfile |
| 91 |
|
| 92 |
if (filenames_only) { |
| 93 |
print FILENAME |
| 94 |
nextfile |
| 95 |
} |
| 96 |
|
| 97 |
if (do_filenames) |
| 98 |
if (line_numbers) |
| 99 |
print FILENAME ":" FNR ":" $0 |
| 100 |
else |
| 101 |
print FILENAME ":" $0 |
| 102 |
else |
| 103 |
print |
| 104 |
} |
| 105 |
} |
| 106 |
END { |
| 107 |
exit (total == 0) |
| 108 |
} |
| 109 |
function usage() |
| 110 |
{ |
| 111 |
print("Usage:\tegrep [-cilnqsvx] [-e pat] [files ...]") > "/dev/stderr" |
| 112 |
print("\tegrep [-cilnqsvx] pat [files ...]") > "/dev/stderr" |
| 113 |
exit 1 |
| 114 |
} |