Inline Regex with Perl

Grep and EGrep are great tools for searching through text files however I often find that I need to only display matching regex groups when looking through log files, a great way to do this is with inline perl regex.

Below is a good example of this in action:

cat docker-compose.yml | perl -lne 'print "$1" if /.*image: (.*)/'

This will search a docker compose file and print out only the docker images names, great for piping to other commands.

Lets break this command down to make it easier to remember, first


Perl officially stands for Practical Extraction and Report Language. Perl was originally a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information.

perl -lne

the -l enables automatic line-ending processing.
the -n causes perl to assume the following loop around your script
the -o ensures the lines are printed

Then inside the quotes we have

print "$1"

this prints the first group in the following regex, you can build on this with multiple group and extra chars with something like:

print "$1-$2"

And finally between the two forward-slashes we have the regex itself,

.*image: (.*)

says print make group 1 everything after the word “image:” for more infomration on regex you can use this great cheatsheet.

Comments are closed.