-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgsel
More file actions
executable file
·43 lines (40 loc) · 1.69 KB
/
Copy pathgsel
File metadata and controls
executable file
·43 lines (40 loc) · 1.69 KB
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
#!/usr/bin/env bash
# gsel - grep and select
#
# TODO: would be nice to open the selected files at the according position. However, vim 8 does not
# support opening several files at custom lines out of the box.
#
# author: andreasl
show_help() {
script_name="${0##*/}"
msg="${script_name}\n"
msg+="Select some of the output of grep with the given parameters and open the according files"
msg+=" in vim.\n"
msg+="\n"
msg+="Usage:\n"
msg+=" ${script_name} <search-pattern>\n"
msg+="\n"
msg+="Examples:\n"
msg+=" ${script_name} '2019' # find & select files that contain '2019'\n"
msg+=" ${script_name} '# TODO' # find & select files that contain '# TODO'\n"
msg+=" ${script_name} -h # print the usage message\n"
msg+=" ${script_name} --help # print the usage message\n"
printf "$msg"
}
[[ "$1" =~ ^(-h|--help)$ ]] && {
show_help
exit
}
grep_cmd='rg -LSn --hidden --no-heading --no-ignore --color=always'
bat_cmd="$(command -v batcat || command -v bat)" # `batcat` on Debian/Ubuntu, `bat` elsewhere
# manually cut; fzf can nicely --delimit similar to `cut`, but fails with file names that have leading & trailing spaces
# shellcheck disable=SC2016 # `$f` must stay unexpanded here; fzf expands it when running the preview
preview_cmd='f="$(printf "%s" {} | cut -d: -f1)"; '"$bat_cmd"' --color=always --style=header,numbers -H{2} --line-range={2}: "$f"'
selections_str="$($grep_cmd "$*" | fzf -m --ansi --delimiter=: --preview="$preview_cmd" | cut -d: -f1)"
[ -n "$selections_str" ] && {
selections=()
while IFS= read -r selection; do
selections+=("$selection")
done <<<"$selections_str"
vim -p "${selections[@]}"
}