Skip to content

Instantly share code, notes, and snippets.

@eksperimental
Last active April 4, 2021 00:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eksperimental/170d663794f1d14cd190 to your computer and use it in GitHub Desktop.
Save eksperimental/170d663794f1d14cd190 to your computer and use it in GitHub Desktop.
ag-l1 : ag – searches files and list them with the line of the first match. Useful to combine with with xargs and your favorite text editor.
#######################################################################
# `ag` list file with first match line number
# Returns a list of files including the first line matched in the file
# emulates the non-implemented option: `ag --files-with-matches-line-number`
# for `ag` (the silver searcher) https://github.com/ggreer/the_silver_searcher
# feature request: https://github.com/ggreer/the_silver_searcher/issues/715
# Usage: just simple use it as you would use `ag -l`, but ommit the -l option
# $ ag-l1 "(pattern)?.*"
# Installation: add this function to your ~/.bash_funcs file
# Download: https://git.io/ag-l1
# https://stackoverflow.com/questions/46163678/get-rid-of-warning-command-substitution-ignored-null-byte-in-input
#result="$(ag --ackmate "$@")"
result="$(ag --ackmate "$@" | tr -d '\0')"
echo "${result}" | grep -P '^\d+;\d+' > /dev/null
if [ $? -eq 0 ]; then
echo "${result}" |
grep -A1 -P '^:.+' |
perl -e '
undef $/;
$s = <>;
$s =~ s/:(.+)\n(\d+);(\d+).*/$1. ":" . $2 . ":" . ($3 + 1)/eg;
print $s;
' |
grep -v -- '--' |
sort -V
else
echo "${result}" |
grep -oP '(?<=:).+' |
while read line; do echo "${line}"; done |
sort -V
fi
# Runs `ag-l1` and open-up files in Sublime text editor.
ag-subl() {
ag-l1 "$@" | xargs subl
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment