one-liners intermediate
How to use Perl one-liners to find and replace across files
Question
How can I search for a pattern across multiple files and replace it using Perl?
Combine -i for in-place editing with glob patterns to process multiple files:
# Replace in all .txt files (with backup)
perl -i.bak -pe 's/old_pattern/new_text/g' *.txt
# Recursively replace in all .pl files
find . -name '*.pl' -exec perl -i.bak -pe 's/foo/bar/g' {} \;
# Or using File::Find in one-liner
perl -MFile::Find -i.bak -e 'find(sub { return unless /\.txt$/; \
local @ARGV = $_; while(<>) { s/old/new/g; print } }, ".")'
# Case-insensitive replace with regex
perl -i.bak -pe 's/error/warning/gi' *.log
# Only replace if line contains another pattern
perl -i.bak -pe 's/foo/bar/g if /baz/' file.txt
# Preview changes without modifying (remove -i)
perl -pe 's/old/new/g' file.txt | diff file.txt -
Always test without -i first, or use -i.bak to create backups. The backup extension can be any string.