To search through text you can use the grep command. It searches files and returns the lines of the file that match a certain string.
The command has the following format:
grep [options] pattern [file]
Here are some of the useful options I use:
Option | Description |
-i | match case insensitive |
-n | Include line number of match in output |
-r | Search recursively through directories |
-F | treat regex litteraly |
-m | Specify the maximum number of matches outputed |
-H / -h | Include filename / Do not include filename |
-A | Specify number of trailing lines after match |
-B | Specify number of leading lines before match |
-o | Only output the matched word, not the whole line |
-l | Output only the names of files containing match |
--colour | highlight the matched keyword in the output line |
Examples
You can also search multiple files eg. all files ending with ‘.log’:
grep "error" "*.log"
And specify multiple patterns:
grep "error|warning" "*.log"
Let’s make some example commands
Highlight the matched word, specify file name and line number and search case insensitively:
grep --colour -Hni "error" "file.txt"
Recursively search in a specified directory
grep -r "error" ./directory
Search all files in current directory with .log extension. Highlight output, maximum number of matches 2, print 1 leading and 1 trailing line
grep --colour -m2 -A1 -B1 "error" "*.log"
Search through directory and only specify name of file containing the match
grep -rl "searchString" /path
Aight, go search!