Skip to Content

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.
%



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...
 

Add a Comment

*0 / 3000 Character Maximum

6 Comments

Filter by:
Newtonick

cat -n

or

cat -b

works too, depending on how you want to nuber the lines

April 11 2007 at 1:53 AM Report abuse rate up rate down Reply
Erica Sadun

Sovak:

grep "." sonnet.txt | wc -l

April 10 2007 at 3:47 PM Report abuse rate up rate down Reply
Sovok

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?

April 10 2007 at 1:10 PM Report abuse rate up rate down Reply
systemsboy

Brilliant! Thank you!

-systemsboy

April 10 2007 at 1:09 AM Report abuse rate up rate down Reply
Erica Sadun

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.

April 09 2007 at 6:49 PM Report abuse rate up rate down Reply
Brian

what does the .*e mean? (terminal n00b)

April 09 2007 at 6:45 PM Report abuse rate up rate down Reply
Buy an ad here

Hot Apps on TUAW

Tweets

© 2012 AOL Inc. All Rights Reserved.