Skip to content
Perl

One-Liners and CLI Tricks

Common Perl one-liners for text processing.

By EZ4Code Team
clione-linertext

Code

# Replace text in-place
perl -i -pe 's/foo/bar/g' file.txt

# Print lines matching pattern
perl -ne 'print if /pattern/' file.txt

# Sum numbers (one per line)
perl -nle '$sum += $_; END { print $sum }' nums.txt

# Field sum (CSV: sum of column 2)
perl -F, -nle '$sum += $F[1]; END { print $sum }' data.csv

# Word frequency
perl -nle '$count{$_}++ for split' file.txt | sort

# Reverse lines
perl -e 'print reverse <>' file.txt

# Print lines 5-10
perl -ne 'print if 5..10' file.txt

# Grep with context (lines before/after)
perl -ne 'print if /pattern/../end/' file.txt

# Trim whitespace
perl -pe 's/^\s+|\s+$//g' file.txt

# CamelCase to snake_case
perl -pe 's/([a-z])([A-Z])/$1_$2/g; $_ = lc' file.txt

# Common flags:
# -e: execute code
# -n: wrap in while (<>) { ... }
# -p: like -n but prints $_ automatically
# -l: auto chomp, adds newline to print
# -i: in-place edit
# -F: set field separator (auto-split into @F)

Explanation

Perl shines at CLI text processing. -e executes code, -n/-p wrap in a loop over input lines, -l auto-chomps and adds newlines, -i edits files in place, -F auto-splits lines into @F. The END block runs after the loop — good for accumulators. Range operator (1..5) selects line ranges. These one-liners often replace awk/sed/grep combos.

More Perl Snippets