Login | Sign up

May 27


0

The power of grep

Comments (0)

The grep command allows you to search files and filter command output based on your search criteria. This command is such a time saver, it is possibly my favorite Linux-only command.

Intro to grep

The grep command allows you to search the output of a command or files for a given string or regular expression. By default, it will display only the lines that contain the search criteria.

Filtering command output

You can pipe the output of a command into grep. This essentially filters the output as it will only display the lines of output that contain your search criteria.

  1. iptables -L INPUT -vn | grep 192.168.1.1

iptables -L INPUT -vn will display your INPUT chain in your firewall. If you had many rules, it could be a little tedious to find the rules that apply to the IP address 192.168.46.1. With this example usage of grep, you will only see the firewall rules that contain that IP address.

Anytime you run a command that has lots of output and you only need to see specific lines, grep is a huge time saver, especially if the output can't be sorted easily.

Searching files

Instead of opening a file and searching using the text editor, you can simply display the lines you are looking for.

  1. grep 1G02Ff-0000m9-KX mainlog

The previous example will display each line in mainlog that has the message ID 1G02Ff-0000m9-KX. This is a useful way to look at each line in the log related to one email message.

You could also use this to quickly look at a configuration parameter (see next example), or to look at each time a certain IP address connected to you access_log.

  1. grep PermitRootLogin /etc/ssh/sshd_config

This will display your setting for PermitRootLogin.


Comments

There are no comments yet.


Post a new comment

Note: Items marked * are required fields

Post a comment

You must login before you can do that.

If you don't have an account, register for free. It's completely private.

Why register

  • rate posts and comments
  • ask questions about posts
  • request new topics/tutorials
  • mark posts as favorites to easily find them again