Perl regular expressions are slightly different from grep (or egrep) regular expressions. grep is sufficient most of the time, but sometimes you may need the extra flexibility of Perl regular expressions, or may just want to test out a regular expression that you will use later in Perl code. This can be done on the command line like so:

perl -ne 'print if /my.regular.expression/' < file

For example, let’s take a file full of random data, named random_data.txt which contains the following:

18838ef123e
f33a244eb1e
4492b3091o9
9o7ef44b22e
77a1194g229

We can write a regular expression to print out the lines which are valid hexadecimal values. The following Perl regular expression can be used for this:

^[\da-fA-F]+$

Using the syntax above, we can print the lines in the file which are valid hexadecimal numbers like so:

perl -ne 'print if /^[\da-fA-F]+$/' < random_data.txt

Which will print:

18838ef123e
f33a244eb1e

Similarly, text can be cat to the perl command like so:

cat random_data.txt | perl -ne 'print if /^[\da-fA-F]+$/'