Friday, February 8, 2008

Count the Ones

"Got a minute?"

A co-worker stuck his head in, yesterday to ask if I could tell him how to count the numer of 1's in a binary string, like "00101101," in a shell script.

"Isn't there a way you can split the string up in Perl?"

"Yeah, but hang on, let me play for a second .... Okay, try this."

$ x=00101101
$ echo ${x//0}
1111
This strips all the 0's.

Now, we just need the string length

$ y=$x{//0}; echo ${#y}
4
We can wrap this all in a function
$ ones() {
> local y=${//1}
> echo ${#y}
> }

$ ones 00101101
4
All this is with shell built-ins, so it's fast, too.

In a little more detail, here's the part about stripping the 0's.

This is basic string substitution

$ echo ${x/0/P}
P0101101
and here's how you replace all the 0's, instead of just one

$ echo ${x//0/P}
PP1P11P1
so you can replace them with nothing

$ echo $x{//0/}
1111
but the final slash can be omitted if there's no replacement
$ echo $x{//0}
1111
Ta-da.

1 comment:

Jeffrey Copeland said...

It's one of those POSIX extensions, so it works in bash, but not ksh, I think.