This is my second post with a handful of pastable commands to improve your use of Bash. If you haven’t seen the first post, you can check it out here. This one is all about GREP. the GNU Regular Expression Parser. A command line utility that has nearly infinite uses and applications.
Grep for all the empty lines and count the number of lines.
grep "^$" <filename> | wc -l
wcis another command line utility that stands for “word count”. The
-loption tells it to count the number of lines.
Output only the number of lines that are matched.
grep -c "^$" <filename>
Get all the lines that don’t match the pattern.
grep -v "FindThisText" myfile.txt
-vstands for invert.
Recursive grep. This traverses the directory and subdirectories.
grep -R "^#" .
In this case, we’re finding every line in a shell script that starts with a comment. Grep is extemely powerful and you can do a lot more with it (perhaps I’ll do another post on it later). But you can always type
man grepto see more options.
If you want to include the lines around the matched lines try the following:
N lines that come after the matched lines.
grep -A <N> "TODO" file.txt
N lines that come before the matched lines.
grep -B <M> "TODO" file.txt
Or just use the
-C option (for context) to include
N lines before and after the matched pattern.
grep -C <N> "TODO" file.txt