Say I have a file with lines like the two following:foo,bar,,baz,xyfoo,,bar,baz,xy,,I would like to count how many times I have ,, (two consecutive commas surrounded by any other character) in each line.My approach so far: I thought I could first get rid of everything but any pair of consecutive commas on each line, and then replace those two commas by a single comma so that I can count them later. How can I do this?The answer above should be (if we substitute the double comma by a single comma throwing everything else away):,,,or simply:12
Counting consecutive repetitions of a specific character (e.g. ,)
sed;regular expression;tr
A Perl one-liner for the job:perl -nle 'print s/(^|[^,]),,([^,]|$)/$&/g' your_fileOr, even shorter, with awk: awk -F',,' '{print NF-1}' your_fileThe awk one would consider ,,,, to be two occurrences of ,,, while the perl one would not count it at all. Choose the one that suits your use case.UpdateFrom your comment, it seems that your original intent was to count the number of empty fields on each line. If that's the case, this Perl one-liner should help (it assumes that there are no quoted fields containing commas):perl -nle 'print scalar grep {//} split/,/' your_fileThe same in awk if Perl is not available:awk -F, 'empty=0;{for(i=1;i<=NF;i++)if($i==)empty++};{print empty}' your_file