-
Notifications
You must be signed in to change notification settings - Fork 2
/
grepe
executable file
·83 lines (70 loc) · 2.62 KB
/
grepe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/bash
# (bash is needed for array support)
USAGE="Usage: ${0##*/} [OPTION]... [--] PATTERN [PATTERN]... [--] [FILE]..."
help() {
echo "$USAGE"
cat <<'/help'
Multi-pattern grep (like `grep -E PAT1\|PAT2...` or `grep -e PAT1 -e PAT2 ...`)
Added/removed options (see `grep --help` for a full list of options):
-e, --regexp=PATTERN REMOVED, use standard grep instead
-f, --file=FILE REMOVED, use standard grep instead
--split Force use of the `grep -e PAT1 -e PAT2 ...` format
/help
version
}
usage() {
printf '%s\nTry `%s --help` for more information.\n' "$USAGE" "${0##*/}" >&2
exit 2
}
version() {
echo 'Part of misc-scripts: https://github.com/adamhotep/misc-scripts'
echo 'grepe 1.0.20200124.1, Copyright 2010+ by Adam Katz, GPL v2+'
exit
}
if [ $# = 0 ]; then usage; fi
if [ "$*" = "-h" ]; then help; fi # support literal `grepe -h` standalone
# programmatically determine GNU grep's options (see below for non-GNU)
GREP_OPTION_LIST="$(grep --help 2>&1 |awk '
/^ *-[a-zA-Z_0-9][ ,]/ {
sub(/^ *-/, "")
sub(/,.*/,"",$1)
if ($2 ~ /^--[^ ]*=/) $1 = $1 ":" # option requires an argument
print $1
}
$1 == "-NUM" {
print "0123456789"
}
' |sort |xargs |sed 's/ //g')-:"
# Non-GNU grep: assume solely POSIX arguments
# via http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
if [ "${#GREP_OPTION_LIST}" -lt 14 ]; then
GREP_OPTION_LIST="EFclqinsvxe:f:"
fi
split= num= ere='-G' delim='\|' sep='--'
args=() pat=()
while getopts $GREP_OPTION_LIST OPT; do
case "$OPT$OPTARG" in
( [0-9] ) num="$num$OPT" ;; # bug: `-1a2` = `-a -12`
( [EP]|-extend*|-perl*) ere="-$OPT" delim='|' ;; # ERE or PCRE
( [ef]* ) echo "Use grep for \`-$OPT\`" >&2; exit 2 ;;
( -file*|-regex*) echo "Use grep for \`--${OPTARG%%=*}\`" >&2; exit 2 ;;
( F|-fixed* ) ere='-F' split=1 sep='' ;; # plaintext match
( G|-basic* ) ere='-G' delim='\|' ;; # BRE - assumes GNU grep
( -help* ) help ;;
( [^-]?* ) args+=("-$OPT" "$OPTARG") ;; # has option
( -split* ) split=1 sep='' ;; # no assumed GNU grep
( V | -ver* ) version ;;
( \? ) usage ;;
( * ) args+=("-$OPT$OPTARG") ;; # long or no option
esac
done
shift $((OPTIND-1))
if [ "${num:--1}" -ge 0 ]; then args+=("-$num"); fi
[ "$split$ere" = 1-P ] && echo "grepe: ignoring --split for -P" >&2
[[ "$ere" = -G && "$GREP_OPTION_LIST" != *G* ]] && ere='' split=1 sep=''
while [ "$#" != 0 ] && [ ! -e "$1" ]; do # -e needed for dirs & grep -r
[ "$1" = -- ] && shift && break
[ "$split" = 1 ] && pat+=(-e "$1") || pat="${pat:+$pat$delim}$1"
shift
done
exec grep "${args[@]}" $ere $sep "${pat[@]}" "$@"