Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

count number of commas in a txt file ?

Status
Not open for further replies.

rab54

Programmer
Joined
Jan 28, 2004
Messages
112
Location
GB
hi gurus -

What is a quick way to do this .... ?

cheers#

Rab
 
Code:
$/=undef;
open FH, "<myfile.txt";
$commaline=<FH>;
close FH;
@array= split (/\,/, $commaline);
$count= $#array;
print "$count commas in file";
 
Another way :
Code:
$/=undef;
open FH, "<myfile.txt";
$commaline=<FH>;
close FH;
($count= ($commaline =~ s/,//g)) += 0;
print "$count commas in file";

Jean Pierre.
 
Or an all-UNIX solution ;-)
Code:
cat test.txt | tr -c -d ',' | wc -c
Cheers, Neil
 
toolkit - fantastic! can you explain how it works?

Code:
cat [b]file.txt[/b]
pipe output to [b]tr[/b]
-cd switches ?
',' - comma
pipe output to [b]wc[/b] (word count)
-c (character count)


Kind Regards
Duncan
 
-d means delete specified characters
-c means complement specified characters

Together, this means delete all characters except those specified. So for an example file:
Code:
qwjdoqdojw,qwoijdoqjwd,oqijdoqjw,
qiwkjdoqiwjdo,
qiwdjoijdqom,
Then cat file | tr -c -d ',' produces:
Code:
,,,,,
Then wc -c is obvious. Cheers, Neil
 
cheers Neil... nice one!


Kind Regards
Duncan
 
Cheers to you all -I used PaulTeg's solution

Rab
 
another way:-

Code:
$commaline = <DATA>;

print split (",", $commaline) - 1 . " commas in file";

__DATA__
this, is, an example, of a, text, file with, commas


Kind Regards
Duncan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top