Using (Again) and


Using ^ (Again) and $

Let's learn how to do more with REs, but match the start and end of a line with the ^ (again) and $ characters.

In order to uniquely match the years specified in the sample file, you can use the start-of-line and end-of-line regular expression characters to stop grep from matching items you do not want matched. For example, if my phone number was in the sample file, I would not want it specified and I can do that with REs.

The characters ^ and $ are commonly referred to as anchors. To anchor something would be to fix something firmly and stably. They will anchor a pattern to the start or end of a line. 1899 and 1999 are both at the beginning of a line so doing this will not be difficult, and will show you the way these REs are used. These are the two rules you should try to commit to memory when using these characters:

  • If ^ is used outside of a range, the ^ character matches the start of a line.

  • $ matches the end of a line. If your pattern falls at the end of a line, you can anchor it in this position with $.

For example, examine how this is done:

 >grep "^1[^7-8][0-9]*" robtest.txt 1899 1999 

This would have only shown me the dates I specified and nothing else, because I specified it clearly using grep and regular expressions.



    SAMS Teach Yourself Unix in 10 Minutes
    Sams Teach Yourself Unix in 10 Minutes (2nd Edition)
    ISBN: 0672327643
    EAN: 2147483647
    Year: 2005
    Pages: 170

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net