Count number of column in a comma delimited file

I have a comma (,) delimited file.

106232145,"medicare","medicare,medicaid",789

I would like to count the number of fields in each line.
I tried the below code

awk -F ',' '{print NF-1}'

This returns me the result as 5 instead of 4. This is because the awk takes "medicare,medicaid" as two different fields instead of one field.:wall:

**In my file, the text field qualifier is "(double quotes)

Please help me with this.

1 Like

Try:

perl -nle 's/".*?"//g;print s/,//g+1' file
1 Like

Another two:

# echo '106232145,"medicare","medicare,medicaid",789'|sed -e 's/"[^"]\{1,\}"//g'|awk '{print NF}' FS=','          
4
# echo '106232145,"medicare","medicare,medicaid",789,'|perl -lane '$count++ while ( /,[\d|"|\n]/g);print $count+1'
4
1 Like
awk -F, '{gsub(/"[^"]*"/,x);print NF}'
2 Likes

Thanks guys!! it works... :slight_smile:
@Scrutinizer: could you please explain your code. bit curious about that

Thanks Scrutinizer :slight_smile: :b:

---------- Post updated at 09:09 PM ---------- Previous update was at 08:16 PM ----------

:confused:
I have to insert a delimiter at the end of each record if it is not present

present data:
10620,"claim processed,paid",reported
 
expected:
10620,"claim processed,paid",reported,

[/COLOR]

can someone please help with this??

Hi, normally you should start a new thread for that...
Try:

sed 's/[^,]$/&,/'file
1 Like

echo "10620,"claim processed,paid",reported" | sed 's/$/,/'

oops! Am sorry... Thanks man...

Also, it will be of great help if you give me some threads for dealing with comma delimited files. I can go through them to get a better understanding about comma delimited files. I have been searching over here and in google but couldn't find something solid, it looks like am missing something.

---------- Post updated at 09:34 PM ---------- Previous update was at 09:30 PM ----------

bhargav, your code will append , to the last field even if it is already there.
scrutinizer's code works fine. It appends "," only if it is not there.