Regular expressions

From Linux 101, The beginner's guide to all things Linux.

Jump to: navigation, search

A regular expression is short hand for a word, a group of words or a sentence.
They are mainly used in pattern matching and in searching and replacing.

Here is a very common use of regular expressions, typing ls *.mp3 will list all the mp3 files you have in the current directory.

The * is a regular expression which means any character in any combination.
So *.mp3 will match with abcdef.mp3, 12.mp3 and Q32.mp3.
However if you do ls B*.mp3 then you'll only list all the files that start with B.

The scripting language Perl has one of the most powerful regular expression engines availible.
This is a simple example of Perl:

$text = "This a REGEX test.  Perl uses REGEX.";

# Replace all occurances of REGEX with regular expressions.
$text =~ s/REGEX/regular expression/g;

print "$text\n";

Copy the text into a file call test.pl and run it.

[example]$ perl test.pl 
This a regular expression test.  Perl uses regular expression.

To learn more about regular expressions then visit this site www.regular-expressions.info

Personal tools