one-liners intermediate

How to write a one-liner to sum numbers in a file

Question

How can I use Perl to quickly sum all numbers in a text file?

Use the -n flag to process each line and -a to autosplit into the @F array:

# Sum all numbers on each line
perl -nale '$sum += $_ for @F; END { print $sum }' numbers.txt

# Sum only the first column
perl -nale '$sum += $F[0]; END { print $sum }' data.txt

# Sum numbers matching a pattern
perl -nle '$sum += $1 while /\b(\d+)\b/g; END { print $sum }' file.txt

# Example file (numbers.txt):
# 10 20 30
# 5 15
# Output: 80

# Flags explained:
# -n: loop through lines without printing
# -a: autosplit line into @F array
# -l: chomp input and add newline to print
# -e: execute code

The END block runs after all input is processed, perfect for aggregation tasks.

Was this helpful?

Related Questions