one-liners intermediate

How to write a Perl one-liner to replace text in files

Question

How can I use Perl from the command line to find and replace text in files?

Use the -i flag for in-place editing and -pe for processing each line:

# Replace 'foo' with 'bar' in file.txt (with backup)
perl -i.bak -pe 's/foo/bar/g' file.txt

# Without backup (dangerous!)
perl -i -pe 's/foo/bar/g' file.txt

# Multiple files
perl -i.bak -pe 's/old/new/g' *.txt

# Case-insensitive replacement
perl -i.bak -pe 's/foo/bar/gi' file.txt

# Replace only first occurrence per line
perl -i.bak -pe 's/foo/bar/' file.txt

The -i flag modifies files in place. Adding .bak creates a backup with that extension. The -p flag wraps your code in a loop that prints each line, and -e allows you to specify code on the command line.

Was this helpful?

Related Questions