Sum a column with awk and display number with printf using comma as thousands separator
Some examples of adding commas as thousands separators using awk and printf.
To add commas as thousands separator with printf:
$ echo 1000000000000 | xargs printf "%'d\n"
1,000,000,000,000
Or:
$ printf "%'d\n" 1000000000000
1,000,000,000,000
To add commas as thousands separator with awk:
$ echo 1000000000000 | awk '{ printf ("%'"'"'d\n", $1) }'
1,000,000,000,000
To sum the first column in this file:
$ cat test.txt
1000000 foo
1000000 bar
1000000 baz
I could use this awk:
$ awk '{ sum+=$1 } END { print sum }' test.txt
3000000
To sum a column of numbers with awk and display the result with commas as thousands separator:
$ awk '{ sum+=$1 } END { printf ("%'"'"'d\n", sum) }' test.txt
3,000,000
Leave a comment