grep Command Tutorial For Ubuntu / Debian Linux

last updated in Categories , ,

I recently switched from MS-Windows XP to Ubuntu Linux. How do I use the grep command on Ubuntu or Debian Linux? Can you give us some practical examples?

The grep command is used to search text file for patterns. A pattern can be a word, text, numbers and more. It is one of the most useful commands on Debian/Ubuntu/ Linux and Unix like operating systems.

grep command syntax on Ubuntu/Debian

The basic syntax is:

grep 'word-to-search' file
grep 'word-to-search' file1 file2
grep 'word-to-search' *.c
grep 'pattern' file
grep 'pattern' file1 file2
grep [options] 'pattern' file1 file2

Open the Terminal and then type the following commands.

grep command examples on Ubuntu/Debian Linux

Search for user named ‘root’ in a text file called /etc/passwd:

grep 'nixcraft' /etc/passwd

Sample outputs:

root:*:0:0:System Administrator:/root:/bin/bash

To search the four files foo, bar, demo, and test for line that contains the string ‘Mangalyaan’, enter:

grep 'Mangalyaan' foo bar demo test

You can search for the phrase ‘Mars orbiter mission’ using the following syntax:

grep 'Mars orbiter mission' isro.txt nasa.txt

To search all text files in the current directory for the phrase ‘Mars orbiter mission’, enter:

grep 'Mars orbiter mission' *

Pass the -r option to the grep command to search recursively through an entire directory tree. In this example, search all files in the current directory and in all of its sub-directories for the phrase ‘Mars orbiter mission’:

grep -r 'Mars orbiter mission' *


grep -R 'Mars orbiter mission' *

You can instructs grep to ignore case i.e. perform a case-insensitive search using the -i option:

grep -i 'nixcraft' *

The above example will search for nixCraft, nixcraft, NIXCRAFT and other patterns:

grep -ir 'nixcraft' *

How do I use grep with other commands?

The syntax is:
command | grep 'search-pattern'
command1 | command2 | grep 'search-pattern'

In this example, run ls command and search for the string/pattern called resume.pdf:

ls | grep resume.pdf
ls -l | grep resumd.pdf
ls -l *.mov | grep 'birthday'
ls -l *.mov | grep  -i 'birthday'

You can search Ubuntu / Debian server log file for errors or the particular string as follows:

grep 'error' /var/log/messages
grep -i 'error' /var/log/messages

To search for the contents of the system message, enter:

dmesg | grep -i 'hd'
dmesg | grep -i 'sd'

The following command will list all hard disk sizes and names on Ubuntu/Debian Linux based system:

fdisk -l | grep 'Disk /dev'

Sample outputs:

Disk /dev/sda: 500.1 GB, 500107862016 bytes

grep tip: Color me beautiful

You can force grep to display output in colors, enter:

grep --color vivek /etc/passwd

Sample outputs:

Fig.01: Surround the matched pattern with color using grep
Fig.01: Surround the matched pattern with color using grep

See also

Posted by: Vivek Gite
