Perl: Command-line regex

By | 2010-03-12

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