Udgivet i

Search text files with grep

How to use the grep tool

The grep tool is built into the operating system, so you don’t need to install it.

The simplest syntax to find a string in a single file using the grep command is:
grep ‘searched-word’ filename

By default, the search with grep is case sensitive.

Let’s gradually add the most useful options to our search.

1. Make the search case-insensitive with the "-i" option:
grep -i 'searched-word' filename
2. Search recursively in all files in a given directory with the "-r" option:
grep -ir 'searched-word' '/directory'
3. Search whole words only with the "-w" option:
grep -irw 'searched-word' '/directory'
4. Print the line numbers in which the searched word was found with the "-n" option:
grep -irwn 'searched-word' '/directory'
5. Search for multiple words syntax:
grep -ir 'word1|word2|word3' '/directory'

Many other useful grep options can be found in the official Grep Manual.