Learnings from GNU GREP and RIPGREP by Sundeep Agarwal'
Ensure that the version of
grep
you're using is 3.7 and above (the default that comes with MacOS is 2.6):grep --version grep (GNU grep) 3.8 Packaged by Homebrew Copyright (C) 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Written by Mike Haertel and others; see <https://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.You can install this (as well as others using Homebrew)
Example file:
programming_quotes.txt
Criteria | grep Command |
Manual Reference |
---|---|---|
Find a word from a text file | grep '[keyword]' [file] |
Link |
Regex pattern matching | grep -F '[regex_pattern]' [file] |
Link |
Case-insensitive searching | grep -i '[keyword]' [file] |
Link |
Inverse matching (ignore lines) | grep -v '[keyword]' [file] |
Link |
Line number | grep -n '[keyword]' [file] |
Link |
Line count | grep -c '[keyword]' [file] |
Link |
Limit output lines | grep -m[lines] '[keyword]' [file] |
Link |
Search multiple strings | grep -e '[first_keyword]' -e '[second_keyword]' [file] |
Link |
Search multiple strings (keywords from a file) | grep -f [keyword_file] [file] |
Link |
List files matching the pattern | grep -l '[keyword]' [file1] [file2] |
Link |
List files NOT matching the pattern | grep -L '[keyword]' [file1] [file2] |
Link |
Suppress filename output (default for single file) | grep -h '[keyword]' [file1] [file2] |
Link |
Show filename output (default for multiple files) | grep -H '[keyword]' [file] |
Link |
Match whole word only | grep -w '[keyword]' [file] |
Link |
Output exact match | grep -x '[keyword]' [file] |
Link |
Common lines between two files | grep -Fxf [file1] [file2] |
|
Extract only matching pattern | grep -o '[keyword]' [file] |
Link |
Example files:
word_anchors.txt
andwords.txt
Typical commands:
Options | Description | Manual Reference |
---|---|---|
-G |
can be used to specify explicitly that BRE is needed | Link |
-E |
will enable Extended Regular Expression (ERE). In GNU grep , BRE and ERE only differ in how metacharacters are specified, no difference in features |
Link |
-F |
will cause the search patterns to be treated literally | Link |
-P |
will enable Perl Compatible Regular Expression (PCRE) (if available) | Link |
^
— start of line$
— end of line