Skip to main content

Perl edit file in place example commands.

# To replace all occurrences of the text `you` with `me` in `file`:
$ perl -pi -e 's/you/me/g' file

# To replace all occurrences of the text `you` with `me` in multiple files:
perl -pi -e 's/you/me/g' file1 file2 file3

# To replace all occurrences of the text `you` with `me`, only on lines that 
# match `we`:
perl -pi -e 's/you/me/g if /we/' file

# To execute a substitution only on lines that have digits in them:
perl -pi -e 's/you/me/g if /\d/' file

# To create a backup of the edited file
$ perl -p -i.bak -e 's/you/me/g' file

# To find all repeated lines in a file:
perl -ne 'print if $a{$_}++' file

# To print out each line with a line number:
perl -ne 'print "$. $_"' file

# To generate a random 8 letter password:
perl -le 'print map { (a..z)[rand 26] } 1..8'


# 
# Resources
# 
# - [Introduction to Perl one-liners](http://www.catonmat.net/blog/introduction-to-perl-one-liners/)
#