Computing.Net > Forums > Programming > Count comma in each line of a text

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Count comma in each line of a text

Reply to Message Icon

Name: Dipali
Date: February 8, 2009 at 21:58:24 Pacific
OS: Unix
Subcategory: Opinions
Comment:

I need to count no. of commas in each line of a csv file which contains text with spaces:
e.g. below text in a file
[mig@cpeuidb bin]$ cat cmt.txt_bkp
this, is a ,comma ,count test1
this, is a ,comma ,count test2
this, is a ,comma ,count test3
Thisisaline,withoutspace,test1
Thisisaline,withoutspace,test2
this, line is ,lacking comma test1
this, line is ,lacking comma test2

i had written script with for loop, problem is, whenever there is a space it splits text into new line, so incorrect count of commas in a line: Please help me out to resolve this problem:
Here is my code for references:

[mig@cpeuidb bin]$ cat cmt.ksh
#!/bin/ksh

. /home/mig/dm_setup

for k in `cat cmt.csv `
do
echo $k > tmp.lst
line_comma_cnt=`awk ' BEGIN { count=0; }
{ for (i=1;i<=length($0);i++)
{
if(substr($0,i,1)=="," ) {count++;}
}
}
END {print count} ' tmp.lst`
echo "New count: $line_comma_cnt"

done
exit 0



Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


PHP image gallery Build up error in python ...



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Count comma in each line of a text

Batch to append text to each line of a txt www.computing.net/answers/programming/batch-to-append-text-to-each-line-of-a-txt/18957.html

Delete Last line of a text file www.computing.net/answers/programming/delete-last-line-of-a-text-file/20179.html

Remove top 6 lines of a text file www.computing.net/answers/programming/remove-top-6-lines-of-a-text-file/19324.html