A Quick Introduction to Unix/More grep examples

From Wikibooks, open books for an open world
Jump to: navigation, search

Anchors[edit]

A search can be constrained to find the string at the beginning of the line with the symbol ^.

Example[edit]

grep '^A' filename

Finds the string A at the beginning of lines.

A search can be constrained to find the string at the end of the line with the symbol $.

Example[edit]

grep '5$' filename

Finds the string 5 at the end of lines.

Counting empty lines[edit]

The combination search string ^$ finds empty lines.

To match any single character[edit]

The meta-character . matches any single character except the end of line character.

Example[edit]

The input file contains these lines:

one
bone
throne
clone

We search with

grep '.one' filename

The results are

bone
throne
clone

The first line doesn't match.

To match zero or more characters[edit]

The meta-character * matches zero or more occurences of the previous character.

Example[edit]

The input file bells containes these lines

bel
bell
belll
be
bet

We search with

grep 'bel*' bells

The results are

bel
bell
belll
be
bet

Example[edit]

The input file is as the previous example. The . is used after the * to require at least a single character.

We search with

grep 'bel*.' bells

The results are

bel
bell
belll

Contrast this with the previous example. Here, we match everything except be.

Example[edit]

The input file is as before.

We search with

grep 'bel.*' bells

The results are

bel
bell
belll

Character lists[edit]

You can use a list of characters surrounded by [ and ] which will match on any single character in the list.

Example[edit]

The input file is lines:

This is the zero line
Here y 
Crosses x

we search with

grep [xyz] lines

The result is

This is the zero line
Here y 
Crosses x

Example[edit]

The input file is as before.

we search with

grep [xyb] lines

The result is

Here y 
Crosses x