Grep flags – the good stuff
21–30 of 53 posts
Re: Grep flags – the good stuff
#22An amazing grep trick that I use all the time: The -e flag can be used to search for multiple terms. A blank -e will search for null. Thus: Lets assume we have a log file with a bunch of relevant stuff, I want to highlight my search term, BUT I also want to keep all the other lines around for context: $ dmesg ...SNIP... [2334597.539661] sd 1:0:0:0: [sdb] Attached SCSI removable disk [2334597.548919] sd 1:0:0:0: [sdb]…
Re: Grep flags – the good stuff
#23Ah, learned the difference between -i and -I. I also like --include and --exclude, especially since it allows regex for which files to look at
Re: Grep flags – the good stuff
#24An amazing grep trick that I use all the time: The -e flag can be used to search for multiple terms. A blank -e will search for null. Thus: Lets assume we have a log file with a bunch of relevant stuff, I want to highlight my search term, BUT I also want to keep all the other lines around for context: $ dmesg ...SNIP... [2334597.539661] sd 1:0:0:0: [sdb] Attached SCSI removable disk [2334597.548919] sd 1:0:0:0: [sdb]…
I always used "-e ^" the same way you're using a null string, to show all lines of the files, each prefixed with the path and filename. Are they equivalent or is there a caveat I should watch out for?
Re: Grep flags – the good stuff
#25 function fvi { grep -rl $1 . | xargs nvim +/$1 }
It greps a directory recursively and opens files which have a pattern and puts the pattern in the search buffer.Re: Grep flags – the good stuff
#26I have problems remembering the mnemonic for -A and -B. I can't get it straight whether it's "before" and "after" or "above" and "below". I always just try one then the other!
Re: Grep flags – the good stuff
#27 #!/bin/sh
usage () {
cat >&2 [paths...]
replace all occurrances of with optionally limited to
(as interpreted by git grep)
-P, --perl-regexp interpret as perl regular expression;
default is to treat it as a fixed string.
__USAGE__
exit 1
}
pattern='-F'
perl='BEGIN {($old, $new) = (shift, shift)} s/\Q$old\E/$new/g'
case "$1" in
-P|--perl-regexp)
shift
pattern='-P'
perl='BEGIN {($old, $new) = (shift, shift)} s/$old/$new/g'
;;
-*) usage
;;
esac
test $# -lt 2 && usage
old=$1; new=$2; shift; shift
git grep -l -z $pattern "$old" -- "$@" |
xargs -0 perl -pi -e "$perl" "$old" "$new"Re: Grep flags – the good stuff
#28I think I have never used grep -r. I'm sure gnu grep has some way to specify which files to search, but why would I learn that syntax as well when I already know find, and exec works (exec + is much faster, but exec ; gets you the results too if your find lacks exec +).
Check out ripgrep
Re: Grep flags – the good stuff
#29https://explainshell.com/explain?cmd=grep+-rilIv
Re: Grep flags – the good stuff
#30Honorable mention for `-q`, which is useful in shell scripts when you don't want the output, just the result code.