Previous Section  < Day Day Up >  Next Section

4.8. GNU Basic grep (grep –G) with Regular Expressions

Basic grep interprets its patterns as basic regular expressions. All of the examples for UNIX basic grep in this section also apply to the GNU version of basic grep, also grep –G or grep '– –basic–regexp'.

The metacharacters used in the examples below are not found in the basic UNIX grep. The examples in this section use the following datafile.

% cat datafile

northwest

NW

Charles Main

3.0

.98

3

34

western

WE

Sharon Gray

5.3

.97

5

23

southwest

SW

Lewis Dalsass

2.7

.8

2

18

southern

SO

Suan Chin

5.1

.95

4

15

southeast

SE

Patricia Hemenway

4.0

.7

4

17

eastern

EA

TB Savage

4.4

.84

5

20

northeast

NE

AM Main Jr.

5.1

.94

3

13

north

NO

Margot Weber

4.5

.89

5

9

central

CT

Ann Stephens

5.7

.94

5

13


Example 4.38.

% grep NW datafile  or

% grep -G NW datafile

northwest             NW       Charles Main           3.0   .98    3     34


EXPLANATION

Prints all lines containing the regular expression NW in a file called datafile.

Example 4.39.

% grep '^n\w*\W' datafile

northwest             NW       Charles Main           3.0   .98    3     34

northeast             NE       AM Main Jr.            5.1   .94    3     13


EXPLANATION

Prints any line starting with an n, followed by zero or more alphanumeric word characters [a–zA–Z0–9_], followed by a nonalphanumeric word character [^a–zA–Z0–9_]. \w and \W are standard word metacharacters for GNU variants of grep.

Example 4.40.

% grep '\bnorth\b' datafile

north                 NO        Margot Weber            4.5   .89    5     9


EXPLANATION

Prints the line if it contains the word north. The \b is a word boundary. It can be used instead of the word anchors (\< \>) on all GNU variants of grep.

    Previous Section  < Day Day Up >  Next Section