Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
2  
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 at 9:03
2  
Think back references. Check the man page for the regular expression syntax. –  Stéphane Chazelas Apr 28 at 9:04

1 Answer 1

In an input file like:


foo

baaar

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

 
discard

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.