1984 – the techblog

(Hopefully) useful various sysadmin and other stuff.

Bash: Handling various versions of wc

I really love the wc tool. For those who don’t know it, it sim­ply counts words, lines, char­ac­ters and bytes of any input it receives on STDIN. You’d be sur­prised how often one needs this func­tion­al­ity! But, as with many things POSIX/UNIX, there are dif­fer­ent flavours avail­able; while many tools have the same name on all sys­tems, they vary in their fea­ture­sets. In the case of wc, this is most vis­i­ble by how the out­put is for­mat­ted: Some ver­sions put white­spaces around the actual val­ues in their out­put – which makes pars­ing it a bit cum­ber­some, espe­cially in case one is inter­ested only in one of the met­rics men­tioned above.

But fear not, BASH to the res­cue! I needed to count the lines in an output:

FILECOUNT=$(( `lsbom ../Bom | wc -l` ))

Enclos­ing the com­mand sub­sti­tu­tion (the part with the back­ticks) in $(( )) causes BASH eval­u­ate the out­put as an arith­metic expres­sion and in doing so, auto­mat­i­cally ignore any white­spaces in the for­mula (nat­u­rally – they have no mean­ing in this con­text). Free trimming!

See also Sec­tion 3.4 of the BASH Beginner’s Guide.

Update: Of course, there are many other ways to do this. Depend­ing on the flavour of your shell, you’re either bet­ter off doing it inside the shell, or with exter­nal com­mands such as expr or tr.

Leave a Reply