Bash: Handling various versions of wc
I really love the
wcÂ tool. For those who don’t know it, it simply counts words, lines, characters and bytes of any input it receives on STDIN. You’d be surprised how often one needs this functionality! But, as with many things POSIX/UNIX, there are different flavours available; while many tools have the same name on all systems, they vary in their featuresets. In the case of
wc,Â this is most visible by how the output is formatted: Some versions put whitespaces around the actual values in their output – which makes parsing it a bit cumbersome, especially in case one is interested only in one of the metrics mentioned above.
But fear not, BASH to the rescue! I needed to count the lines in an output:
FILECOUNT=$(( `lsbom ../Bom | wc -l` ))
Enclosing the command substitution (the part with the backticks) in
$(( )) causes BASH evaluate the output as an arithmetic expression and in doing so, automatically ignore any whitespaces in the formula (naturally â€“ they have no meaning in this context). Free trimming!
Update: Of course, there are many other ways to do this. Depending on the flavour of your shell, you’re either better off doing it inside the shell, or with external commands such as