Regular expressions

From Linuxintro
Revision as of 07:36, 20 September 2008 by imported>WikiSysop (→‎Match string1 OR string2)

Regular expressions allow you to formulate patterns to search for. Here's an example: It is easy to search for the string "Sep" in a file, you do it with

grep "Sep" file

This gives you all lines containing the string "Sep". But what do you do if you only want lines starting with "Sep", for example, to read all lines in your syslog regarding september? Then you need regular expressions. It works like this:

grep -E "^Sep" /var/log/messages

gives you all entries for september in your syslog. And there is much more you can do with regular expressions.

Escaping

The characters ^ and \ are seen as control-characters. ^ means "at the beginning of a line". With a backslash, you can escape these control-characters, meaning they act as body-characters again:

grep "^hallo" file

finds all occurrences of "hallo" at the beginning of a line in file.

grep "\^hallo" 

finds all occurrences of "^hallo" in a file

grep "\\^hallo"

finds all occurrences of "\^hallo" in a file

grep "\\\\^hallo"

finds all occurrences of "\\^hallo" in a file And so on...

Matching

Match string1 OR string2

grep -E "Sep|Aug" file

prints all lines from file that contain "Sep" or "Aug".

Match a group of characters

grep -E "L[I,1]NUX" file

prints all lines from file that contain "LINUX" or "L1NUX"