How to use grep command in 5 minutes
Grep is linux command that stands for globally search for a regular expression and print matching lines. It basically prints out what you are searching for, on the command line.
Use case: Trying to find specific log in your log file.
Here are the basic syntax.
grep [OPTION] PATTERNS [FILE]
Let’s say I am searching for log file in the point where some user with id:123 is requesting to log in.
grep 'login request error. input id:123' ./server.log
This will print out all the occurrences where login request error is taken place, with specific input id.
However, this does not give much information, other than the error occurred.
To specify where I want to search within that log file, I can add these commands to search for 10 lines before, and 5 lines after the occurrence.
grep -A10 -B5 'login request error. input id:123' ./server.log
This will give me the more information about the underlying cause of why the user has failed to login.
If you want to specify even more, you can get only last occurrence of that instance.(There could be multiple instances where same log has been written, but irrelevant to the current situation)
grep -m1 -A10 -B5 'login request error. input id:123' ./server.log
This will give me 1 match(-m1), 10 lines after match(-A10), 5 lines before match(-B5) in server.log.
This way, I can only get the latest login request error for input id:123.
There are more options to grep command, but these commands alone can save you ton of time searching for error logs.(Coming from a personal experience)