Ricardo Almeida
Ricardo Almeida

Reputation: 157

Linux Shell - Grep command

I'm having a problem using grep with these options: \{n\} , \{n,\} and \{n,m\} . I have a file named "new" with this lines:

aaaa
aaa
aa
a

When i use grep 'a\{1\}' new i get this output:

aaaa
aaa
aa
a

So, basically, this command will show me the lines that include 1, or more, consecutive occurrences of the character "a" right?

Also, grep 'a\{1,\} new will do the same thing as grep 'a\{1\}' new ? Because i get the same output for both.

The last one, \{n,m\} , i cant really understand what it does.

I would really appreciate if anyone could help me out.

Upvotes: 1

Views: 1493

Answers (2)

EverythingRightPlace
EverythingRightPlace

Reputation: 1197

From man grep:

   Repetition
       A regular expression may be  followed  by  one  of  several  repetition
       operators:
       ?      The preceding item is optional and matched at most once.
       *      The preceding item will be matched zero or more times.
       +      The preceding item will be matched one or more times.
       {n}    The preceding item is matched exactly n times.
       {n,}   The preceding item is matched n or more times.
       {n,m}  The  preceding  item  is  matched at least n times, but not more
              than m times.

That example grep 'a\{2,3\}' new matches also the line with aaaa because of the first three (or 2) a. The rest of the line isn't important.

If you want that really only 2 or 3 consecutive a are matched, you could use the -o flag. But be aware that this would output aa and aaa from a line with aaaaa. To avoid this you have to use additional information, like in the example line breakings ^ and $.

Btw. I would suggest to use the -E flag (or egrep which is the same) so you have extended regex support. You don't have to escape the brackets then.

For input

aaaaa
aaaa
aaa
aa
a

a call of grep -o -E '^a{2,3}$' will give the output:

aaa
aa

Upvotes: 2

yakiang
yakiang

Reputation: 1634

grep 'a\{n,m\}' new means grepping at least n number of a and at most m number of a from new.
For example, grep 'a\{2,3\}' new will output

aaaa
aaa
aa

the last line doesnot match because it only has ONE a.
For a{n,\}' , omitting m means any number larger than or equal to n.

Upvotes: 2

Related Questions