← Back to articles

Perl: Command-line regex

A few one-liners I keep reaching for: filtering and replacing with regex straight from the Perl command line, including in-place file editing with automatic backups.

Tedd

A few command-line tricks for Perl:

\t

  • **Filter based on regex (like grep -E) ** cat file.txt | perl -n -e ‘print if /regex.*matched/’

\t

  • Replace based on regex cat file.txt | perl -n -e ‘s/regex.*matched/replacement/gi’

\t

  • **Replace based on regex inside file (will change file) ** perl -pi -e ‘s/regex.*matched/replacement/gi’ *.txt

\t

  • **Replace based on regex inside file (will change file) and make a backup of original file with .bak extension. ** perl -pi.bak -e ‘s/regex.*matched/replacement/gi’ *.txt

Written by Tedd · Oslo, Norway

Follow the journal via RSS