Filed under: Tips and tricks, Odds and ends, Terminal Tips
Terminal Tip: the joy of nl
Too often overlooked, nl provides a very useful shell command. As you can see here, when issued, it numbers the lines of a text file. But that's certainly not all that this little utility can do. My favorite feature allows you to count the occurrences of a regular expression. Use the -bp flag to tell nl to count all the lines that match that expression. For example:
% nl -bp"So.*e" sonnet.txt
Shall I compare thee to a summer's day?
Thou art more lovely and more temperate:
Rough winds do shake the darling buds of May,
And summer's lease hath all too short a date:
1 Sometime too hot the eye of heaven shines,
And often is his gold complexion dimm'd;
And every fair from fair sometime declines,
By chance or nature's changing course untrimm'd;
But thy eternal summer shall not fade
Nor lose possession of that fair thou owest;
Nor shall Death brag thou wander'st in his shade,
When in eternal lines to time thou growest:
2 So long as men can breathe or eyes can see,
3 So long lives this and this gives life to thee.
%

Reader Comments (Page 1 of 1)
Brian said 6:47PM on 4-09-2007
what does the .*e mean? (terminal n00b)
Reply
Erica Sadun said 6:53PM on 4-09-2007
It's part of the regular expression. "So.*e" means to match any string starting with a capital S, a lower case o, followed by any number of characters (.*, where the dot is a wildcard and * means zero or more occurances) followed by a lower-case e.
Reply
systemsboy said 1:09AM on 4-10-2007
Brilliant! Thank you!
-systemsboy
Reply
Sovok said 2:16PM on 4-10-2007
Thanks. I made a script with this, which returns the number of non-empty lines:
#!/bin/bash
# Count Lines
case "$1" in "") echo "Usage: ${0##*/} filename"; exit $E_PARAM;;
esac
nl $1 | tail -n 1 | awk '{print $1}'
Does anyone know a shorter/faster way?
Reply
Erica Sadun said 3:48PM on 4-10-2007
Sovak:
grep "." sonnet.txt | wc -l
Reply
Newtonick said 1:53AM on 4-11-2007
cat -n
or
cat -b
works too, depending on how you want to nuber the lines
Reply