Text Searching
Introduction to GREP Command
grep
(Global Regular Expression Print) is a powerful command-line utility used for searching text using patterns. It is commonly used in Unix-based systems like Linux and macOS to search for specific strings or patterns within files.
Practice file
You can download this file to practice grep
.
wget -O sample.txt https://raw.githubusercontent.com/Donders-Institute/hpc-wiki-v2/master/docs/linux/exercise/gcutError_recon-all.log
Basic Usage
- To search for a specific text within a file:
grep "used" sample.txt
- To perform a case-insensitive search:
grep -i "home" sample.txt
info
My apologies for the large output. Type clear
in the terminal to remove all your output.
- To search for whole words only:
grep -w "Program" sample.txt
- To display line numbers along with matching lines:
grep -n "used" sample.txt
Advanced Usage
Basic Regular Expressions
.
: Matches any single character.*
: Matches zero or more of the preceding character.
Example:
grep "a.b" sample.txt
Extended Regular Expressions
Use -E
to enable extended regular expressions:
|
: Alternation (OR).+
: Matches one or more of the preceding character.?
: Matches zero or one of the preceding character.
Example:
- Search for
cat
ordog
grep -E "cat|dog" sample.txt
- To search for multiple patterns:
grep -e "max" -e "limited" sample.txt
Searching Recursively
- To search recursively through directories:
grep -r "home" /etc/defaults
Inverting Match
- To display lines that do not match the pattern:
grep -v "hi" sample.txt
Cleanup
- You can now remove the sample file once you're done:
rm sample.txt
External Resources
The grep
command is an essential tool for searching and processing text data. Mastering its usage will greatly enhance your ability to manage and analyze large volumes of text efficiently.