1. Overview

grep is a Linux-based command-line tool that searches for a pattern across a file’s contents. If we search for a pattern containing some special characters, then nullifying its inbuilt shell characteristics is critical to getting the expected search results.

This tutorial will expound on different methods of using the special characters literally in the grep search pattern.

2. Special Characters in Linux

In Linux, there’s a set of characters that impart a particular meaning in the shell — for instance, # for comments, double-quote (“) for variables and command substitution, $ for variable expression, and & for background job, to name a few.

Now, let’s create a CSV file named employees.csv as an example that we’ll use throughout the tutorial:

tools@sandbox1:~/baeldung$ cat employees.csv
#Name,Age,Team
Mary Smith,45,DevOps
John,"",NetOps
Jane Doe,25,DevOps
James,38,NetOps
Mary Robert,30,SRE
William,"",SRE

In this case, we’re searching for the lines that have “SRE” or “DevOps” words. Subsequently, the pipe (|) command will perform the OR operation:

tools@sandbox1:~/baeldung$ grep -E "SRE|DevOps" employees.csv
Mary Smith,45,DevOps
Jane Doe,25,DevOps
Mary Robert,30,SRE
William,"",SRE

Suppose we’re interested in searching for the lines that have double-quotes. We may think it’s trivial at first:

tools@sandbox1:~/baeldung$ grep -E """ employees.csv
>

However, the shell will assume that the search pattern is incomplete and awaits the closure of the double-quotes.

3. Using the Special Characters Literally

In the above cases, we want to use the special characters literally without their innate shell interpretations. Quoting and escaping are two methods that enable the usage of special characters literally.

3.1. Quoting

Quoting nullifies the shell’s inherent behavior for special characters. We should use a single quote between the characters to implement this method.

Due to its robust feature, we call the single-quote ‘strong quoting’, whereas we say that the double-quote is “weak quoting”.

tools@sandbox1:~/baeldung$ grep -E '"' employees.csv
John,"",NetOps
William,"",SRE

3.2. Escaping

Generally, the backslash (*\*) character is yet another option to quash the inbuilt shell interpretation and tell the shell to accept the symbol literally.

Let’s have a closer look at the usage:

tools@sandbox1:~/baeldung$ grep -E "\"" employees.csv
John,"",NetOps
William,"",SRE

4. Conclusion

Both quoting and escaping are used to remove the inbuilt shell interpretation for special characters.

However, quoting is best applied to the whole grep pattern to turn off the special character meaning, and escaping is implemented to the specific part of the grep pattern wherever it’s needed.