brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a python -c one-liner adds up a column of numbers from a pipe

Python
~/tips/tip-python-c-sum-numbers-stdin

printf '12.5\n3\n4.25\n' | python3 -c 'import sys; print(sum(float(l) for l in sys.stdin if l.strip()))'

Total a list of numbers from another command without awk or a spreadsheet.

When you want the total of a column of numbers in the terminal, the awk syntax is easy to forget. A short Python line reads like what it does.

printf '12.5\n3\n4.25\n' | python3 -c 'import sys; print(sum(float(l) for l in sys.stdin if l.strip()))'
# 19.75

cut -d, -f3 expenses.csv | tail -n +2 | python3 -c 'import sys; print(sum(float(l) for l in sys.stdin if l.strip()))'

sys.stdin gives you the piped input line by line, float() turns each line into a number and ignores the newline, and sum adds it all up. The if l.strip() part skips empty lines, which otherwise crash it with a ValueError. The second example takes the third column of a CSV and skips the header line with tail.

Since it’s plain Python, it’s easy to change. Swap sum for max, or wrap it in len and a list to count, or use statistics.median when the average lies.

It’s strict about input, and I count that as a plus. A line like 12,50 with a comma as decimal separator, or a stray word, stops it with an error instead of being silently treated as zero the way awk would. For money, swap float for decimal.Decimal to avoid rounding noise in the last digits. Single quotes around the code keep the shell from touching it.

Further reading: python -c, sys.stdin

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link