Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Input file:

A    1,2,3,4      #length($2)=4
B    1,2          #length($2)=2
C    9,8,7,6,5,4  #length($2)=6

Expected output:

12 #4+2+6

A method like: awk -F '[\t,]' '{print length($2)}' but working on the whole file.

share|improve this question
Can you clarify what you mean by length($2)? Do you mean "number of characters" (like awk does) excluding commas, or do you mean number of fields, like "number of commas + 1"? For example, your "length($2)" for 12,13 is 2 or 4? – jw013 Aug 20 '14 at 17:19
More like "number of commas +1" so that length$2 for 12,13 is 2. – Dovah Aug 20 '14 at 20:44

4 Answers 4

up vote 7 down vote accepted

If there are no other columns with commas, this will do it:

awk -F, '{c+=NF} END {print c+0}' file
share|improve this answer
This is a short and the way it should be done using simple syntax! – val0x00ff Aug 20 '14 at 18:02


awk '{s += split($2, a, ",")}; END{print s+0}' file
share|improve this answer
@Gnouc, when a file with no records is processed print s+0 would report 0 whereas print s would just print a blank. I think reporting 0 is more intuitive – 1_CR Aug 20 '14 at 17:36

If there are no other columns with commas, that resolves to counting the number of lines and commas:

tr -cd ',\n' < file | wc -c
share|improve this answer


$ awk '{split($2,a,",");s += length(a)};END{print s+0}' file

or if your number is only one digit:

$ awk '{gsub(",","",$2);s += length($2)};END{print s+0}' file
share|improve this answer
You may want to update your answer based on comments to the original question. Evidently OP means to count the commas and does not mean length($2) literally. – jw013 Aug 20 '14 at 21:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.