Perl: Command-line regex

A few command-line tricks for Perl:

  • Filter based on regex (like grep -E)
    cat file.txt | perl -n -e ‘print if /regex.*matched/’
  • Replace based on regex
    cat file.txt | perl -n -e ‘s/regex.*matched/replacement/gi’
  • Replace based on regex inside file (will change file)
    perl -pi -e ‘s/regex.*matched/replacement/gi’ *.txt
  • 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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Tedds blog

Subscribe now to keep reading and get access to the full archive.

Continue reading