-
Notifications
You must be signed in to change notification settings - Fork 2
/
findgrep
executable file
·93 lines (80 loc) · 2.86 KB
/
findgrep
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
84
85
86
87
88
89
90
91
92
#!/bin/bash
# Author: Gokberk Cinbis, 2021
set -e
function __increment_argi__() # just increment argi variable
{
argi=$((argi+1))
}
function __decrement_argi__() # just decrement argi variable
{
argi=$((argi-1))
}
function __print_help__ ()
{
echo "findgrep [-i] [-n <ptn>] [-e <ext>] [--debug] <regexp>"
echo "Search all files recursively, list files and matches for those matching with <regexp>"
echo ""
echo "ARGUMENTS"
echo "-i Optional ignore case option."
echo "-n <ptn> Optional name argument, restrict search to file names matching <ptn>"
echo "-e <ext> Optional extension argument, restrict search to *.<ext>."
echo "--list-only List matching files only, not their content."
echo "--non-binary Ignores binary files (uses grep's --binary-files=without-match option), can speed up."
echo "--debug Don't execute the command, just print the final find command."
echo "<regexp> Regular expression."
exit 1
}
function __main__()
{
local narg=$#
local regexp="${!narg}" # last argument
if [ $narg -lt 1 ]
then
__print_help__
fi
findargs=()
grepargs=()
debug=0
argi=0 # argument reading index
for (( argi=1; argi<=$((narg-1)); argi++ )); do
if [ "${!argi}" == '-i' ]; then
grepargs+=('--ignore-case')
elif [ "${!argi}" == '--debug' ]; then
debug=1
elif [[ "${!argi}" == '-n' ]]; then
__increment_argi__
if [ $argi -eq $narg ]; then
__print_help__ # we'd read <regexp> as <ext> incorrectly
fi
# doesnt work: findargs+=('-name' "\"*.${!argi}\"")
findargs+=('-name' "${!argi}")
elif [[ "${!argi}" == '-e' ]]; then
__increment_argi__
if [ $argi -eq $narg ]; then
__print_help__ # we'd read <regexp> as <ext> incorrectly
fi
# doesnt work: findargs+=('-name' "\"*.${!argi}\"")
findargs+=('-name' "*.${!argi}")
elif [[ "${!argi}" == '--non-binary' ]]; then
__increment_argi__
grepargs+=("--binary-files=without-match")
elif [[ "${!argi}" == '--list-only' ]]; then
__increment_argi__
grepargs+=("--files-with-matches")
else
command echo "Unrecognized argument: {!argi}"
__print_help__
fi
done
# -H filename
# -n line number
if [ $debug -eq 1 ]; then
echo command find -L . "${findargs[@]}" -type f -exec grep -H -n --color "${grepargs[@]}" "$regexp" {} \;
else
command find -L . "${findargs[@]}" -type f -exec grep -H -n --color "${grepargs[@]}" "$regexp" {} \;
fi
# Example simple case: command find . -type f -L -name "*.$1" -exec grep -H --color "$2" {} \;
}
# ok with multiple quoted arguments
__main__ "$@"
exit 0