how do i write a regular expression using grep to find lines that start with 'O' or 'o' AND contain 2 consecutive 'c' characters.
grep '^[Oo]c{2}' filename
You were 99% there, very close, just:
grep '^[Oo]c\{2\}' filename
or equivalent:
grep -E '^[Oo]c{2}' filename
^[Oo]c
, the caret ^
matches beginning, and any of the characters within []
are matchedc{2}
, where you meant to match the previous character c
, exactly two times.{
as a meta-character for use with this kind of matching, so we change it to \{
and \}
to make it recognize itgrep -E '^[Oo]c{2}' filename
If that does not match, maybe copy a sample of the contents of your test filename
that does include what you are trying to match, and update the question to display it, in case there is something else we missed.
You already have a pure regex answer but here's a more grepish one:
grep -i ^occ file
The -i
flag tells grep to do case insensitive matching. It is defined by POSIX so should be present in any grep implementation. Once you have that, since you only want two c
characters, there's no reason to complicate things by using {2}
; cc
is both shorter and clearer. However, note that the -i
applies to the entire reguex so this will also match cC
or CC
or Cc
. If you don't want that, use @user454038's approach instead.
If you also need to match lines where the consecutive c
s are not directly after the o
, use this instead:
grep -i '^o.*cc' file
-i
makes the entire regexp case-insensitive, i.e. it will match CC
, Cc
, and cC
as well as cc
. If the homework question does not explicitly say that's allowed, the OP will probably be marked down for it.
{}
as\{\}
^[Oo]c\{2\}
and^[Oo]cc
. e.g. trygrep -c '^[Oo]cc' /usr/share/dict/words
, that will count all words beginning withOcc
orocc
(on my system, 123 such words)