Skip to content
shellhacks.dev
Text Processing

Treat a pattern as a literal string

Search for a literal string with grep -F so the dot, the star and the brackets lose their regular expression meaning, which also avoids escaping mistakes.

1 min read
Summarize in AI

A pattern such as v1.2 or a[0] is a regular expression to grep, so it matches more than you meant or fails to compile.

Shell
printf 'v1.2\nv1x2\nitems a[0]\n' > data.txt
grep 'v1.2' data.txt
echo ---
grep -F 'v1.2' data.txt
echo ---
grep 'a[0]' data.txt
echo "status: $?"
grep -F 'a[0]' data.txt
Text
v1.2
v1x2
---
v1.2
---
status: 1
items a[0]

-F makes grep read each pattern as a list of fixed strings, separated by newlines, with no metacharacters. In the first run the dot matches any character, so v1x2 is a hit. A bracket pair is a character class, so a[0] looks for a0. Fixed strings are described in the grep manual. The tool does not need a second pass of escaping, which is useful when the string comes from a variable.

Fixed strings also turn off alternation and anchors, so ^ and | become ordinary characters. The speed gain over a regular expression depends on the input and was not measured here, so treat correctness as the reason to use it. Use -- before a pattern that starts with a hyphen.

Share

More snippets

Text Processing

Search recursively and skip binary files

Skip binary files in a recursive grep with --binary-files=without-match, short form below. Otherwise GNU grep 3.8 prints a notice for every binary hit.

1 min read
Text Processing

Count the matches per file

Count the matching lines in each file with grep -c. With several files grep prefixes each count with the name, and -h removes the prefix for one total.

1 min read
Text Processing

Count every occurrence not just lines

Count every occurrence of a word with grep -o piped to wc -l, because grep -c counts the lines that match and a line with three hits counts as one.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.