how to find the count of commas in a string excluding the ones in double quotes

Hi,
my requirement is to find the count of commas in a string excluding the ones in double quotes.
For example:
If the input string is

abc,xyz.com,lmhgdf,"abc, 401 street","tty,stt",45,23,45

The output should be 7

awk '{gsub("\"[^\"]*\"","");n=gsub(",","");print n}' infile
1 Like
$ echo 'abc,xyz.com,lmhgdf,"abc, 401 street","tty,stt",45,23,45' | \
sed 's/"[^"]*"//g' | grep -o , | wc -l
       7
$ 
1 Like
my $str='abc,xyz.com,lmhgdf,"abc, 401 street","tty,stt",45,23,45,aa,bb,"a,b","a,bb,aaa,ss,,,,,",a,a,a,a';
my @tmp = $str=~/(,)(?=
[^"]*$
|
(?:(?:[^",]*,)*(?:"[^"]*",)*(?:[^",]*,)*)*(?:[^",]+|"[^"]*")$
)/xg;
print $#tmp+1;

Thanks a lot guys...
This worked for me !!!

And another one:

perl -MText::ParseWords -nle'
    print parse_line(",",0, $_) - 1;
    ' infile

Using bartus11

$ echo 'abc,xyz.com,lmhgdf,"abc, 401 street","tty,stt",45,23,45' | awk -F"," ' { gsub("\"[^\"]*\"",""); print NF-1 } '
7

using bash:

var='abc,xyz.com,lmhgdf,"abc, 401 street","tty,stt",45,23,45'
commas="${var//\"[^\"]*\"/,}"
commas="${commas//[^,]}"
echo ${#commas}
7