Using and


Using [] and ^

In this section, we will learn more about REs, particularly when using and negating ranges using the [] and ^ characters.

You've noticed that the robtest.txt file you created and have been using has the years 1899 through 1999 inside of it. We will use grep again in conjunction with REs to match the years that only fall in the 2000 range. To do this, you can specify a range using REs as follows: [<starting point>-<ending point>]. The starting and ending points can be numbers or ranges within the alphabet.

For example, type the following:

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

This example lets Unix search robtest.txt for anything that is in the 1[8-9][9-0] range, which is only 1999 and 1899. It couldn't be anything from the year 2000 to 2006. The 1 before the bracket specifies that the years can range from either 1[8 which means 18, or 1[9, which specifies 1900. The second bracket specifies the same thing. The second part of the year (the last two digits) has one of them specified alreadythe 9. Now, apply the same concept. The 9 before the bracket 9[ will specify that the last two digits of the year can range anywhere from either 9[0 which means 90, or 9[9, which specifies 1999. Once you have mastered this concept, it should be easier to apply more complex REs.

Using ranges can help you pull certain values out of files that you may need, such as the two years we just showed. You can expand the capability of the range by applying the negation operator as well. The character ^ negates a range if it is used at the start of the range specification. Negating a range will match the opposite of what the range matches.

For example, type the following:

 > grep "1[^8-9]9[0-9]*" robtest.txt 2006 2005 2004 2003 2002 2001 2000 

Notice that you now match anything that isn't in 1899 through 1999.



    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