Posts tagged ‘piping’

Looks like using Linux is really bound to slowly – but steadily – improve your commandline-fu. As evidence, today I wanted to share a little piece of shell acolyte’s magic that I managed to craft without very big trouble. It’s about counting lines in files – code lines in code files, to be specific.

For a single file, getting the number of text rows is very simple:

$ wc -l some.file

142 some.file

Although the name wc comes from “word count”, the -l switch changes its mode of operation into counting rows. The flexibility of this little program doesn’t end here; for example, it can also accept piped input (as stdin):

$ cat some.file | wc -l

142

as well as multiple files:

$ wc -l some.file other.file

142 some.file

54 other.file

196 all

or even wildcards, such as wc -l *.file. With these we could rather easily count the number of lines of code in our project:

$ wc -l **/*.py

3 foo/__init__.py

189 foo/main.py

89 foo/utils.py

24 setup.py

133 tests.py

438 all

Unfortunately, the exact interpretation of **/* wildcard seems to vary between shells. In zsh it works as shown above, but in bash I had it omit files from current directory. While it might make some sense here (as it would give a total without setup script and tests), I’m sure it won’t be the case all projects.