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=00101101This strips all the 0's.
$ echo ${x//0}
1111
Now, we just need the string length
$ y=$x{//0}; echo ${#y}We can wrap this all in a function
4
$ ones() {All this is with shell built-ins, so it's fast, too.
> local y=${//1}
> echo ${#y}
> }
$ ones 00101101
4
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
P0101101
$ echo ${x//0/P}so you can replace them with nothing
PP1P11P1
$ echo $x{//0/}but the final slash can be omitted if there's no replacement
1111
$ echo $x{//0}Ta-da.
1111
1 comment:
It's one of those POSIX extensions, so it works in bash, but not ksh, I think.
Post a Comment