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.

I have a file containing random codes. Each code has ten characters in it, and I am trying to grep codes in the file that have at least 2 occurrences of a character. I am doing this:

grep DD* [filename]

This finds codes with 2 occurrences of the character 'D', but it also shows codes that have just 1 occurrence of 'D'. How can I change my regular expression to only show codes with 2 occurrences?

share|improve this question
add comment

1 Answer

* in a regular expression is a quantifier meaning the previous entity repeated 0 or more times.

Just remove the quantifier:

grep DD filename

Note that the above will also match lines with 3 or more occurrences of “D”.

In case you want any character, not only “D”, 2 or more times:

grep -E '(.)\1' filename

If you want “D” exactly 2 times:

grep -E '([^D]|^)DD([^D]|$)' filename
share|improve this answer
add comment

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.