-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhifi
executable file
·101 lines (84 loc) · 2.72 KB
/
hifi
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
96
97
98
99
100
101
#!/bin/zsh
export HISTFILE=~/.zsh_history
search_terms=()
search_mode="-c"
exclude_terms=()
# Function to display usage instructions
usage() {
echo "Usage: hifi [-w|-c] <term1> [<term2> ...] [-x <exclude1> [<exclude2> ...]]"
echo "Options:"
echo " -w Search for commands containing all terms with word boundaries"
echo " -c Search for commands containing all terms (default)"
echo " -x Exclude specified terms from the result"
exit 1
}
# Function to perform search using grep and sequential filtering
hifigrep() {
local search_terms=("$@")
local first_term="${search_terms[1]}"
local result
# Search for the first term with or without word boundaries
result=$(grep -E "$first_term" "$HISTFILE")
# Loop through the remaining terms
for ((i = 2; i <= ${#search_terms[@]}; i++)); do
local term="${search_terms[i]}"
# Search for the term with or without word boundaries
temp_result=$(echo "$result" | grep -E "$term")
result="$temp_result"
done
echo "$result"
}
# Function to exclude specified terms from the result
hifiexclude() {
local result="$1"
for exclude_term in "${exclude_terms[@]}"; do
result=$(echo "$result" | grep -E -v "$exclude_term")
done
echo "$result"
}
# Function to check for overlap between excluded terms and search terms
checkExcludedOverlap() {
local search_terms=("$@")
local excluded_terms=("${exclude_terms[@]}")
for term in "${search_terms[@]}"; do
for exclude_term in "${excluded_terms[@]}"; do
if [[ "$term" == *"$exclude_term"* ]]; then
echo "Warning: Excluded term '$exclude_term' overlaps with search term '$term'."
return 1 # Return 1 to indicate overlap
fi
done
done
return 0 # No overlap found
}
# Process command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-w) search_mode="-w";;
-c) search_mode="-c";;
-x) shift
exclude_terms+=("$@")
checkExcludedOverlap "${search_terms[@]}" || exit 1 # Terminate if overlap detected
break;;
*) search_terms+=("$1");;
esac
shift
done
# Check if at least one search term is provided
if [ ${#search_terms[@]} -eq 0 ]; then
echo "Error: At least one search term is required."
usage
fi
# Adjust patterns based on search mode
if [ "$search_mode" = "-w" ]; then
for ((i = 1; i <= ${#search_terms[@]}; i++)); do
search_terms[i]="\\b${search_terms[i]}\\b"
done
fi
# Read history file and perform search
if [ -f "$HISTFILE" ]; then
result=$(hifigrep "${search_terms[@]}")
result=$(hifiexclude "$result")
echo "$result"
else
echo "History file not found."
fi