How to tell grep to ignore special characters in a string (solution)

Back in the old days I thought that any pattern that was including in single-quotes with the Unix grep command meant that the pattern inside the string was completely ignored by grep. But these days I have to escape special characters with a backslash character, which is really annoying. This example shows what I mean:

$ grep '\[NOTE\]' *adoc
01-D-intro.adoc:[NOTE]
10-D-eclipse.adoc:[NOTE]
14-D-assembly.adoc:[NOTE]

In that example I’m searching Asciidoc files for the pattern [NOTE], but I have to use backslash characters before the two bracket characters to get my pattern to work. I finally got tired of doing that and looked at the man page for grep, and it turns out that you can use its -F option to ignore special characters that are in between the quotes, like this:

$ grep -F '[NOTE]' *adoc
01-D-intro.adoc:[NOTE]
10-D-eclipse.adoc:[NOTE]
14-D-assembly.adoc:[NOTE]

That’s a much better solution. Here’s what the grep man page says about this option:

-F, --fixed-strings
    Interpret pattern as a set of fixed strings 
    (i.e. force grep to behave as fgrep).

That’s actually not terribly helpful, but I thought I’d include it here for completeness. :)

Speaking of completeness, you can also use grep’s -n argument to show matching line numbers:

$ grep -Fn '[NOTE]' *adoc
01-D-intro.adoc:45:[NOTE]
10-D-eclipse.adoc:31:[NOTE]
14-D-assembly.adoc:113:[NOTE]

In summary, if you wanted to see how to configure grep so it will ignore special characters inside of quotes, I hope this solution is helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.