Now and then I have to find some information in text files – logs, config files, etc. with a unique enough approach: I have a hostname or parameter name to search by, but the actual information I'm interested in is not found in the same line. Simple grep will just not do – so I'm using one of the really useful command line options for the grep command.
Default grep Behaviour
By default, grep shows you just the lines of text files that match the parameter you specify.
I'm looking for the IP address of the home office server called "server" in .ssh/config file.
Here's what default grep shows me:
greys@maverick:~ $ grep server .ssh/config Host server
So it's useful in a sense that this confirms that I indeed have a server profile defined in my .ssh/config file, but it doesn't show any more lines of the config so I can't really see the IP address of my "server".
Show Next Few Lines with grep
This is where the -A option (A – After) for grep becomes really useful: specify number of lines to show in addition to the line that matches search pattern and enjoy the result!
I'm asking grep to show me 2 more lines after the "server" line:
greys@maverick:~ $ grep -A2 server .ssh/config Host server HostName 192.168.1.55 ForwardAgent yes
Super simple but very powerful way of using grep. I hope you like it!
Leave a Reply