Sunday 15 October 2017

Avoid extra typing "grep -v grep"

We frequently use grep filter to filter and print strings of characters that we look for in a file or the output of a command.

We might be searching for a process in the ps- ef command's output and we end up with the grep command itself being displayed in the results.

For example, if I use grep to search for sshd processes in the 'ps -ef' output I get the following result:


[root@pbox6 ~]# ps -ef | grep ssh
root       1823      1  0 10:20 ?        00:00:00 /usr/sbin/sshd root       2656   1823  1 10:22 ?        00:00:00 sshd: root@pts/1 root       2660   1823  0 10:22 ?        00:00:00 sshd: root [priv] sshd       2661   2660  0 10:22 ?        00:00:00 sshd: root [net] root       2683   2662  0 10:22 pts/1    00:00:00 grep ssh



This could be an issue if we intend to count the number of processes and use the subsequent result in a script.

An option to remove grep from the search result would be to pipe the output to "grep -v grep".

[root@pbox6 ~]# ps -ef | grep ssh | grep -v grep
root       1823      1  0 10:20 ?        00:00:00 /usr/sbin/sshd
root       2656   1823  0 10:22 ?        00:00:00 sshd: root@pts/1
root       2660   1823  0 10:22 ?        00:00:00 sshd: root@notty
root       2686   2660  0 10:22 ?        00:00:00 /usr/libexec/openssh/sftp-server

But in an effort to avoid typing more than we need to, we could just enclose the first or last character of the string being searched for in square brackets to denote a character class and doing so would omit the grep command itself from showing up in the search result.

[root@pbox6 ~]# ps -ef | grep [s]sh
root       1823      1  0 10:20 ?        00:00:00 /usr/sbin/sshd
root       2656   1823  0 10:22 ?        00:00:00 sshd: root@pts/1
root       2660   1823  0 10:22 ?        00:00:00 sshd: root@notty
root       2686   2660  0 10:22 ?        00:00:00 /usr/libexec/openssh/sftp-server
[root@pbox6 ~]#
[root@pbox6 ~]# ps -ef | grep ss[h]
root       1823      1  0 10:20 ?        00:00:00 /usr/sbin/sshd
root       2656   1823  0 10:22 ?        00:00:00 sshd: root@pts/1
root       2660   1823  0 10:22 ?        00:00:00 sshd: root@notty
root       2686   2660  0 10:22 ?        00:00:00 /usr/libexec/openssh/sftp-server


I hope this quick type has been helpful for you.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...