Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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 – iruvar 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.