How can I count how many elements are separated with comma in a given column of a file (tab_delimited), using awk or sed?


AC    1,23,5
DC    2,8,89

Would return:

AC    3
DC    3
$ awk -F '[\t,]' '{print $1, NF-1}' some_file


  • -F sets the field separator, i.e. either tab or comma
  • $1 references the first field
  • NF is a built-in variable that contains the number of fields in a record
  • the awk statement is executed for each record (i.e. for each line)
awk -v col=2 -F '\t' '{$col=gsub(",", "", $col)+1; print}'

col is a parameter representing the analyzed column number and -v assigns 2 to it.

-F '\t' sets the field separator to the tab character1. gsub returns the number of substitutions, so it's being used to count the number of commas. The result is assigned to analyzed column and the final print displays all the columns.

$ cat input 
AC  1,23,5
DC  2,8,89
XX  3,4,5,6,7   YYY,ZZZ
$ awk --assign col=2 -F '\t' '{$col=gsub(",", "", $col)+1; print}' < input
AC 3
DC 3

1 Some awk implementations might not parse \t and in that case you can use some Bash specific quoting - $'\t' - which will pass the tab character itself to awk.

  • What significance has the $ before '\t' ? Testing your command without it gives the same results, at least with gawk and nawk. – maxschlepzig Jul 12 '14 at 20:20
  • @maxschlepzig, see this comment from Stack Overflow. I got the $ from over there. It also made no difference for me too with bash-4.2.47-2.fc20.x86_64. – Cristian Ciupitu Jul 12 '14 at 20:22
  • I see - then it is only needed for awk versions that don't interpret the 2 character string \t as tab-character field separator. – maxschlepzig Jul 12 '14 at 20:29
  • @maxschlepzig, I've removed the $ to make the command line more portable, less Bash specific. By the way, Greg's wiki has a better explanation than the ABS guide: "Of these, $'...' is the most common, and acts just like single quotes except that backslash-escaped combinations are expanded as specified by the ANSI C standard". – Cristian Ciupitu Jul 12 '14 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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