Things I Learned #22: How to Count Words in Powershell

2 minute read til learning   dotnet   azure   powershell Comments

As I’ve mentioned in previous TIL’s, I’m not a power user of Powershell. I use it when I need to and can generally figure things out. Sometime in 2015, I started working on what I had hoped would be the book version of my old “Going Independent” conference workshop. I still had the knowledge, it just wasn’t appropriate to go around telling people, “hey, you should go indie!” while I was working for The Man, so I figured put it out as a book and call it good.

I wrote bits and pieces of several chapters, and after a long writing session, I was always interested how much I had written. I wrote (and still do) everything in Markdown either in Vim or in VSCode, but at the time, there wasn’t a good way on Windows to get the word count without pasting it into Word and using its tools. On my Mac or Linux, it was easy.

> wc filename.md

The output of the wc command on my Mac

The output shows lines, words, and characters. If you provide a wildcard for the filename, it will list all files with the lines, words, and characters and total them at the end of the output. If I just wanted to see words, I could use the -w argument, lines would be the -l argument, and of course, -c would give you the character count by itself.

The output of wc when using a wildcard for the file specifier

TIL

Unfortunately, I did a fair amount of writing on my Windows machine where wc wasn’t an option, so I needed to come up with a Powershell solution. While not nearly as elegant as just calling a single command, I figured out how to combine the necessary cmdlets to get me the output I was looking for.

PS> Get-Content filename.md | Measure-Object -line -word -character

The output of a Powershell command to return the number of lines, words, and characters in a file

The script I created only used the -word parameter, but for this post, I wanted to show how you could get some other information with the same command.

It may not be 100% accurate (either method), but it’s close enough for me.

I ended up writing two scripts: wordcount.ps1 that wrapped all that up into a simple command, and wordcount.sh just so I could run the same thing on both platforms.

Bonus Tip

I have since found a great extension for VSCode named, of all things, Word Count. It adds an entry to the status bar so I can easily see how much I’ve written. Granted, it only shows word count, but that’s almost always what I care about.

The VSCode status bar showing the Word Count extension in action.

I hope you enjoyed this tip!


A seal indicating this page was written by a human

Updated:

Comments