Difference between revisions of "Regular expressions"

From Linuxintro
imported>WikiSysop
imported>WikiSysop
Line 4: Line 4:
 
  grep -E "^Sep" /var/log/messages
 
  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.
 
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 =
 
= Matching =

Revision as of 10:20, 14 September 2008

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 that contain "Sep" or "Aug".