Filter any command output easily using pipes and the ‘grep’ command.

Basic usage

  • Search a word in a file. This command will output every line that contains some_word in file.txt.
    grep some_word file.txt
    
  • Search a word in a command output. You can pipe the output of a command to grep to look for a word.
    $ lsblk | grep sda
    sda      8:0    0 465.8G  0 disk 
    ├─sda1   8:1    0   499M  0 part 
    ├─sda2   8:2    0   100M  0 part /boot
    ├─sda3   8:3    0    16M  0 part 
    ├─sda4   8:4    0 143.4G  0 part 
    ├─sda5   8:5    0 127.3G  0 part /
    └─sda6   8:6    0 194.5G  0 part 
    

Patterns

  • You can use regular expressions. You need to put single quotes around them.
    $ lsblk | grep 'sda[1|2]'
    ├─sda1   8:1    0   499M  0 part 
    ├─sda2   8:2    0   100M  0 part /boot
    
    $ lsblk | grep '/$'
    ├─sda5   8:5    0 127.3G  0 part /
    

Command options

  • -v: look for the inverse.
  • -i: ignore case.
  • -c: print the count of matching lines.
    $ lsblk | grep -c sda
    7
    
  • -o: print only the match part of a matching line.
  • -R: search recursively. -r does not follow symlinks.
    grep -R someword posts/*