Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Jul 292013

How to sum a particular column of a CSV file with awk


Assume you have a CSV file like the following (only contain number)


How do you sum the nth column of this file? It is easy with the use of awk

e.g. Assume you want to sum the 2nd column:

# awk -F "," '{ sum += $2 } END { print sum }' test.txt

Sep 172010

Multiple separators in awk


Sometimes when you split a string using awk, you need to support more than 1 separators, you can use the -F option.


# cat foo.txt | awk -F "[ ?]" '{print $7}'

Now the awk split by a space and by a ?.

Jan 272010

Extract column data using awk


A simple awk command print the 1st column of top command

# top -bc -n1 | awk '{print $1}'

If you want to specify the field separator, you can do the following

# awk -F':' '{print $1}' /etc/passwd

Which print the 1st column of file /etc/password, as if they are split by :