Take the 2-minute tour ×
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.

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

Exemple:

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

Would return:

AC    3
DC    3
share|improve this question
add comment

2 Answers 2

up vote 5 down vote accepted
$ awk -F '[\t,]' '{print $1, NF-1}' some_file

where

  • -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)
share|improve this answer
add comment
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
XX 5 YYY,ZZZ

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.

share|improve this answer
    
What significance has the $ before '\t' ? Testing your command without it gives the same results, at least with gawk and nawk. –  maxschlepzig Jul 12 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 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 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 at 20:49
add comment

Your Answer

 
discard

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.