UNIX / Linux: awk Add Two Numbers

How do I add two numbers using awk? How do I calculate all incoming number stream on fly and display the total using awk?

AWK is a programming language designed for processing text-based data, either in files or data streams. Calculating incoming stream is not a big deal with awk. You can add two numbers as follows:

# add 2 + 5
echo |awk '{ print 2+3 }'
# add incoming 10 + 10
echo 10  | awk '{ print $1 + 10}'

Create a text file called numbers as follows /tmp/numbers:


To add numbers, enter:

awk '{total += $1}END{ print total}'  /tmp/numbers

Sample outputs:


Use the ps command output (stream) to calculate total size of php-cgi process using awk, enter:

ps -aylC php-cgi  | grep php-cgi | awk '{total += $8}END{size=  total / 1024; printf "php-cgi total size %.2f MB\n", size}'

Sample outputs:

php-cgi total size 2004.21 MB

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum