0

When I run these commands, I get output like this:

Screenshot of Terminal

Here are the commands and output, in textual form:

$ cat exte i ii iii iiii iiiii iiiiii 

This works fine:

$ egrep --color i\{4,5\} exte iiii iiiii iiiiii 

I guess it should show color only one or two "i" of a line, but the output colors everything:

$ egrep --color i\{1,2\} exte i ii iii iiii iiiii iiiiii 

Similarly, I can't see the extended regex working here:

$ egrep --color i? exte i ii iii iiii iiiii iiiiii $ egrep --color i+ exte i ii iii iiii iiiii iiiiii 
4
  • 1
    Use word boundaries. Commented May 22, 2016 at 17:12
  • 1
    Jup, with the i{1,2} you get multiple matches for the same line. So either use a word boundary, or use ^i{1,2}$ so it considers also the start and end of the line. Commented May 22, 2016 at 17:26
  • 1
    and for the last two examples with i+ and i?, the lines contain several i's each single one matching (none-or-more)(?) or (one-or-more)(+) so everything is correct, explain what/why exactly you expect Commented May 22, 2016 at 20:16
  • 1
    By default grep prints the line that matches a regexp so it's behaving exactly as designed. You might want the behavior you'd get with the -o option to print the string that matches the regexp instead of the line that contains the regexp. Commented May 22, 2016 at 21:47

1 Answer 1

1

This command colors all, because in your file have that many i's.

$ egrep --color i\{1,2\} exte i ii iii iiii iiiii iiiiii 

Take the example of third line in output. You didn't specified any constraint for a line matching starting of the line or ending of the line. So, it matches one by one. So, the first two i's in the second third line is matched. For the third i it checks the condition, that time also the condition is true. So, it matches all.

If you want more clear output you can use the -o option to what are all matching.

-o:-

Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

$ egrep --color i? exte 

The ? mark in grep regular expression, it matches zero or one occurrence of the preceding character. So, It is also working like the above command. All the i's matching one by one for the regex.

$ egrep --color i+ exte 

The + means match one or more occurrence of the preceding character. So, it matches all the i's for line by line for a single occurrence.

If you want to see the output as clear format you have to use the -o option.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.