Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My task is using grep to find how many times the same character occurs twice in a row.
I was thinking about something like this but it isn`t working

grep '[a-zA-z]{2}' *.txt | wc

How can achieve such a task with grep?

share|improve this question
In aaa, does a appear twice in a row once ([aa]a, aa[a?]) or twice ([aa]a, a[aa])? – Stéphane Chazelas Apr 28 '14 at 9:03
Think back references. Check the man page for the regular expression syntax. – Stéphane Chazelas Apr 28 '14 at 9:04

In an input file like:



I count 4 occurrences of a character being repeated: oo, <NL><NL>, aa and aa.

To count the repeating characters within a line, you could use perl-style regular expression like (.)(?=\1). For repeating newline, you can count the empty lines except if it's the first line.

You could get close with GNU grep

grep -Po '^$|(.)(?=\1)' | wc -l

But that would count the first empty line, so you could remove it first or add a xx on empty lines except the first one:

sed '1!s/^$/xx/' | grep -Po '(.)(?=\1)' | wc -l
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.