Searching Text
Grep searches inside files for lines that hold a word. It prints only the lines that match.
Find the errors
Two lines hold the word ERROR.
$ cd ~/practice
$ grep ERROR data/logs.txtAdd line numbers
The errors sit on lines 3 and 5.
$ cd ~/practice
$ grep -n ERROR data/logs.txtIgnore case
Small error matches capital ERROR too.
$ cd ~/practice
$ grep -i error data/logs.txtCount the matches
The count is 2, the same as the two lines above.
$ cd ~/practice
$ grep -c ERROR data/logs.txtExample
$ cd ~/practice
$ grep -r ERROR .
$ grep -c INFO data/logs.txtKey points
- Use grep to find lines that hold a word.
- Grep prints the whole line, not just the word.
- The -n option adds the line number to each match.
- The -i option matches capital and small letters alike.
- The -r option searches every file below a folder.
- The -c option counts the matching lines.
- Grep reads the lines for you, so a long file stays quick to search.
In this example, grep -r searches every file below this folder. Both errors come from data/logs.txt, and the file name prints before each line. Then grep -c counts the INFO lines in the same file, and the count is 2.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How many lines in data/logs.txt hold the word ERROR?