Featured image of post How to Count Whitespace in the Terminal

How to Count Whitespace in the Terminal

Properly!

How to Count Whitespace in the Terminal

Just a quick post. I might update this later if I improve the content but for now I have found a quick way to reliably count whitespaces in text in the terminal.

Initially I thought to cat the contents of the file and use tr to trim to just spaces and then to count the remaining space characters with wc -m.

Annoyingly there is a new line included at the end which you can’t see but is still counted. Therefore I devised another way using printf which, if you do any coding in C or the such like, you will be familiar with but you might not be aware that it works in the terminal too.

For example:

1
printf "1 2 3 4" | tr -cd '[:space:]' | wc -m

Produces a result of 3. That’s we wanted and that’s what we got. It’ll do for now!

Built with Hugo
Theme Stack designed by Jimmy