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.
Useless use of 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}' fileSimilarly:
grep -v pattern file | awk '{commands}'can be re-written as:
awk '!/pattern/{commands}' fileUseless use of
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}' fileSimilarly:
grep -v pattern file | sed 's/foo/bar/g'can be re-written as:
sed -n '/pattern/!{s/foo/bar/p}' fileUseless use of
grep
in conditionsIf 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 fican be re-written as:
if [[ $var == *pattern* ]]; then # do something fior, if your pattern is a regex, rather than a fixed string, use:
if [[ $var =~ pattern ]]; then # do something fi
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.