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}
This strips all the 0's.

Now, we just need the string length

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

$ ones 00101101
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}
and here's how you replace all the 0's, instead of just one

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

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

1 comment:

Jeff said...

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