Operating System - Linux
1748240 Members
3730 Online
108759 Solutions
New Discussion юеВ

Re: how to count special characters?

 
SOLVED
Go to solution
Gemini_2
Regular Advisor

how to count special characters?

what is the shell command to find the number of the certain character

for example, I have a string

1,2,3,4,6

how do I find the number of "," in the string?

thank you

13 REPLIES 13
Pete Randall
Outstanding Contributor

Re: how to count special characters?

grep ',' string |wc -c


Pete

Pete
RAC_1
Honored Contributor
Solution

Re: how to count special characters?

echo 1,2,3,46 | tr -cd '\,' | wc -c
There is no substitute to HARDWORK
Pete Randall
Outstanding Contributor

Re: how to count special characters?

Forget that idea, it didn't work.


Pete

Pete
Kent Ostby
Honored Contributor

Re: how to count special characters?

If your data is in the file "inputfile", type:
awk '{FS=",";}{print $NF-2}' < inputfile

If there are no commas, it will issue a "-1 or -2" for that line.

For the line above, it will yield 4
"Well, actually, she is a rocket scientist" -- Steve Martin in "Roxanne"
Jean-Luc Oudart
Honored Contributor

Re: how to count special characters?

Hi

try

A="a,b,c,d,e,"
echo $A | awk -v var1="," '{print gsub(var1," ");}'


Regards
Jean-Luc
fiat lux
Gemini_2
Regular Advisor

Re: how to count special characters?

thanks everyone for your speedy reply..

"echo 1,2,3,46 | tr -cd '\,' | wc -c"

is a very interesting use of "tr".

May I ask more questions?
can you explain more on "tr -cd"
-c is "first complement SET1", what does it mean?...
Sandman!
Honored Contributor

Re: how to count special characters?

The "-c" option tells tr what characters NOT to translate..."-c" (complement) option.

For example the following command makes the non-alphabetic characters in a file stand out by translating them to a number sign.

# tr -c '[A-Z][a-z]' '[#*]' < input_file


hope it helps!!!
Sandman!
Honored Contributor

Re: how to count special characters?

Pasted below is a C program that you can compile and execute for counting commas (or any character with slight modifications) within your input files.

==============================================================
#include
#define SPLCHR ','

main()
{
int nc, c;

while ((c = getchar()) != EOF)
if (c == SPLCHR)
++nc;
printf("Number of commas in the input string is: %d\n", nc);
}
==============================================================

cheers!
Arturo Galbiati
Esteemed Contributor

Re: how to count special characters?

Hi,
echo 1,2,3,4|awk -F, '{print NF-1}'

This counts the number of fields separted by ',' minus 1 giving you the number of the separtor.

HTH,
Art