grep ‘foo’ 2012-2013.txt | awk ‘BEGIN{ sum=0.0}{ sub(“,”,””,$7); sum +=$7}END{ print “$” sum}’
$682444
Tutorial details | |
---|---|
Difficulty | Easy (rss) |
Root privileges | No |
Requirements | awk |
Time | 5 minute |
Floating-point numbers or “real” numbers are that have a fractional part. awk uses double-precision floating-point numbers to represent all numeric values. In other words, all numbers in awk are floating-point numbers i.e. all calculation done using floating-point numbers.
Example: Awk floating point calculation
The following example uses a file called trade.txt, which contains a list of week names as well as four profit values per week:
week1 12.5 12.5 13.5 18.5 week2 11.5 11.10 12.10 13.70 week3 8.5 8.10 8.5 12.5 week4 9.5 11.5 13.5 16.5 week5 8 7 13 17
The following awk program takes the file trade.txt and prints the sum of all four values:
awk '{ sum = $2 + $3 + $4 + $5; print $1, sum }' trade.txt
Sample outputs:
week1 57 week2 48.4 week3 37.6 week4 51 week5 45
The following awk program takes the file trade.txt and prints the average of all four values:
awk '{ sum = $2 + $3 + $4 + $5; avg = sum/4; print $1, sum , avg}' trade.txt
Sample outputs:
week1 57 14.25 week2 48.4 12.1 week3 37.6 9.4 week4 51 12.75 week5 45 11.25
To avoid surprises use printf to format text to make your output more beautiful and meaningful:
awk '{ sum = $2 + $3 + $4 + $5; avg = sum/4; printf "%s: $%.2f ($%05.2f)\n",$1, sum, avg}' trade.txt
OR
awk '{ sum = $2 + $3 + $4 + $5; avg = sum/4; printf "%s: $%.2f ($%5.2f)\n",$1, sum, avg}' trade.txt
Sample outputs:
week1: $57.00 ($14.25) week2: $48.40 ($12.10) week3: $37.60 ($ 9.40) week4: $51.00 ($12.75) week5: $45.00 ($11.25)
To fix your problem, replace the following awk code
grep 'foo' 2012-2013.txt | awk 'BEGIN{ sum=0.0}{ sub(",","",$7); sum +=$7}END{ print "$" sum}'
with:
grep 'foo' 2012-2013.txt | awk 'BEGIN{ sum=0.0}{ sub(",","",$7); sum +=$7}END{ printf "$%.2f\n", sum}'
You can skip the grep command and use awk as follows to match and perform sum of all $7:
awk '/foo/{ sub(",","",$7); sum = old + $7; old=sum}END{ printf "$%.2f\n", sum}' 2013-2014.txt
Recommended readings
- See awk command man page for more info.
🐧 1 comment so far... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
There’s no need for the old variable: