5

I have been learning linux commands and got this error. My text is here:

Fred apples 20
Susy oranges 12 
Mark watermellons 12
Robert pears 4
Terry oranges 9
Lisa peaches 7
Egemen aaaa 12
Susy oranges 12
Mark grapes 39
Anne mangoes 7
Greg pineapples 3
Oliver rockmellons 2
Betty limes 14

I searched for the lines not ending with 2. My command:

egrep '2.+' mysampledata.txt

But interestingly I got these two lines:

Fred apples 20
Susy oranges 12

I tried some other arguments for these command and changed the sequence of the lines. I did not got any false result.

What's wrong with this construction?

1
  • 2.+ does not specify a line ending in 2. You might instead look to 2$.
    – HalosGhost
    Feb 22, 2015 at 22:26

2 Answers 2

8

If you want the lines not ending with '2' try the following:

grep '[^2]$' <filename>

Here '$' matches the end of the line, '[^2] means anything other than '2'. So, '[^2]$' means match any character other than '2' at the end of the line.

Your command egrep '2.+' mysampledata.txt, will search for the lines containing '2' and then any character occurring one or more times. So, the output should be:

Fred apples 20

The additional line Susy oranges 12 might be due to an space wrongly put at the end of the line.

Edit: The following will consider any number of whitespaces or any non-printable characters at the end too:

grep -v '2[[:blank:][:cntrl:]]*$' <filename>

This means print the lines that does not have '2' or '2' followed by any number of whitespaces or control characters at the end of the line.

0
6

You should do:

grep -v '2 *$' mysampledata.txt

The -v option reverses the match. This supports lines with spaces at the end, since this is the case on your file and you do not seem to want

Susy oranges 12 $

to be output (the $ here marks the end of line).

1
  • @EgemenSarımaden Note that only my answer correctly deals with your problem (supporting spaces at the end of the lines). Add a space after Betty limes 14 to see the difference.
    – vinc17
    Feb 22, 2015 at 23:55

You must log in to answer this question.