-
Notifications
You must be signed in to change notification settings - Fork 0
/
count
executable file
·95 lines (89 loc) · 2.48 KB
/
count
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
93
94
95
#!/bin/bash
# INSTALL: symlink or copy this file to /usr/local/bin
#
# Count files in a directory with a given ending
#
# Usage:
# $ count [-a] [-d directory] [-E] [-L] [-r] [-v] [regex]
#
# Positional Arguments:
# * [regex]: Passed to grep to filter files, defaults to match all files
#
# Options:
# * [-a]: Include hidden files and directories
# * [-d directory]: Relative path for folder to count files for, default none
# * [-E]: Enable extended regular expressions (i.e. egrep or grep -E)
# * [-L]: Follow symbolic links
# * [-r]: Recursive, count files from file_path downwards
# * [-v]: Invert the sense of the match, count non-matching files
#
# Notes:
# Hidden files (starting with ".") are displayed in the counts without
# a "*." prefix to distinguish them from actual file extensions
# Parese CLI optional and positional arguments -------------------------------
while getopts "ad:ELrv" opt; do
case $opt in
a)
hidden=true;;
d)
file_path=$OPTARG;;
E)
extended=true;;
L)
symbolic=true;;
r)
recursive=true;;
v)
invert=true;;
\?)
exit 1;;
:)
exit 1;;
esac
done
hidden=${hidden:-false}
extended=${extended:-false}
symbolic=${symbolic:-false}
recursive=${recursive:-false}
invert=${invert:-false}
file_path="$(pwd)/$file_path"
if [[ ! -d "$file_path" ]]; then
echo "$file_path is not a directory"
exit 1
fi
shift $((OPTIND - 1))
if [[ -z "$1" ]]; then
all=true
fi
all=${all:-false}
regex=\"${1:-.*}\"
# Find files matching criteria -----------------------------------------------
if [[ "$symbolic" == true ]]; then
files="find -L ${file_path}"
else
files="find ${file_path}"
fi
if [[ "$recursive" == false ]]; then
files="${files} -maxdepth 1"
fi
if [[ "$hidden" == false ]]; then
files="${files} -not -path '*/\.*'"
fi
files="${files} -type f -printf '%f\n'"
# Filter and count based on file endings -------------------------------------
if [[ "$all" == true ]]; then
substitutions="sed '/\./! s/.*/None/' | sed -r 's/^.+\./\*\./'"
cmd="${files} | ${substitutions} | sort | uniq -c | sort -nrk1"
else
if [[ "$extended" = true ]]; then
search="egrep ${regex}"
else
search="grep ${regex}"
fi
if [[ "$invert" == true ]]; then
search="${search} -v"
fi
cmd="${files} | ${search} | wc -l"
fi
# Run composite command ------------------------------------------------------
eval $cmd