Skip to content
shellhacks.dev
Text Processing

Match a Repeated Word with a grep -E Backreference

Find a repeated word such as "is is" with grep -E and a backreference. Backreferences in ERE are a GNU extension, and -i is needed to also catch The the.

1 min read
Summarize in AI

A proofreading pass should flag words typed twice in a row, and a plain pattern cannot say "the same word again".

Shell
text='this is is a test. The the end.'
echo "$text" | grep -oE '\b(\w+)\s+\1\b'
echo "$text" | grep -oiE '\b(\w+)\s+\1\b'
Text
is is
is is
The the

A group around a word pattern captures one word, and a backreference to group one matches the same text again, so the pattern finds a word followed by white space and itself. The word-boundary anchors at both ends keep it from matching inside longer words such as "this is". The first command misses "The the" because the comparison is case-sensitive, and -i in the second also makes the backreference ignore case. Backreferences are part of basic regular expressions in POSIX, and GNU grep also allows them in extended mode.

Strict POSIX ERE has no backreference, and the word-boundary, word-character and space shorthands are GNU additions, so the pattern fails on BSD and macOS grep unless it is rewritten with [[:space:]]. A match across a line break needs the whole text in one record, as grep -z gives. Backreferences make the match engine slow on long lines.

Taggedgrepregex
Share

More snippets

Get new posts by email

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

Unsubscribe in one click. No spam, ever.