SKIP grep, use AWK
Over the years, I’ve seen many people use this pattern (filter-map):
$ [data is generated] | grep something | awk '{print $2}'
but it can be shortened to:
$ [data is generated] | awk '/something/ {print $2}'
You (probably) don’t need grep
Following this logic, you can replace a simple grep with:
$ [data is generated] | awk '/something/'
This will implicitly print lines that match the regular expression.
If feel lost, I’ve got an illuminating series of posts about awk for you.
Why would I do this?
I can think of 4 reasons:
- it’s shorter to type
- it spawns one less process
- awk uses modern (read “Perl”) regular expressions, by default – like
grep -E
- it’s ready to “augment” with more awk
But “grep -v” is OK…
It’s possible to emulate grep -v
with awk, but it’s not a good idea:
$ [data is generated] | awk '/something/ {next} 1'
- it’s uglier
- it’s longer than
grep -v
- “what’s does that even do?!” – it requires a deeper understanding of awk
UPDATE:
Many people have pointed out that “grep -v” can be done more consicely with:
$ [data is generated] | awk '! /something/'
which isn’t too bad at all.