Useless Use of Grep
Most of us are familiar with the infamous Useless Use of Cat Award which is awarded for unnecessary use of the
Useless use of
Useless use of
Useless use of cat command. A while back, I also wrote about Useless Use of Echo in which I advised using here-strings and here-docs instead of the echo command. In a similar vein, this post is about the useless use of the grep command.
grep | awk
awk can match patterns, so there is no need to pipe the output of grep to awk. For example, the following:
grep pattern file | awk '{commands}'
can be re-written as:
awk '/pattern/{commands}' file
Similarly:
grep -v pattern file | awk '{commands}'
can be re-written as:
awk '!/pattern/{commands}' file
grep | sed
sed can match patterns, so you don't need to pipe the output of grep to sed. For example, the following:
grep pattern file | sed 's/foo/bar/g'
can be re-written as:
sed -n '/pattern/{s/foo/bar/p}' file
Similarly:
grep -v pattern file | sed 's/foo/bar/g'
can be re-written as:
sed -n '/pattern/!{s/foo/bar/p}' file
grep in conditions
If you find yourself using grep in conditional statements to check if a string variable matches a certain pattern, consider using bash's in-built string matching instead. For example, the following:
if grep -q pattern <<< "$var"; then
# do something
fi
can be re-written as:
if [[ $var == *pattern* ]]; then
# do something
fi
or, if your pattern is a regex, rather than a fixed string, use:
if [[ $var =~ pattern ]]; then
# do something
fi