Skip Navigation
Site HomeSearch

On-Line Reference:
RedHat Linux Unleashed

Did this help?
... or
Donate at PayPal®...

 
Tux the Pengin

OK, here's a freebie: A simulation of the old text-based Star Trek game we used to play on HP 2100's using a Teletype ASR-33 as a console: StarTrek Game

nl command for MacOS X

Linux has a neat little command called "nl" that will number lines in a file for you. I recently had need of that on my Mac and was disappointed to find that it isn't included.

I do most of my scripting in PHP these days so I tried implementing the nl function in PHP, however that required PHP compiled with the commandline feature, which maybe not everyone has, and also required an alias to be added to your local .bashrc file.

It is simpler to create a nl script in Perl and then save it (as root) into /usr/bin/:

Open a Terminal, start the either the vi or Pico editor and copy/paste or type the following script. Save as a file called "nl":

#!/usr/bin/perl -w
#
# nl
#
# Implements the Linux 'nl' command for Mac OS X systems
#
# Numbers non-empty lines in text files
#
# Usage: commandline invocation:
#
#    $ nl infile outfile     (numbers non-empty lines)
#        or
#    $ nl -a infile outfile  (numbers ALL lines)
#
#########################################################

if($#ARGV < 1) {
  die "Insufficient arguments.";
}
if($#ARGV == 2) {
  ($op, $in, $out) = @ARGV;
} else {
  ($in, $out) = @ARGV;
  $op = "";
}
if($in eq $out) {
  die "Infile/outfile names must differ.";
}
open (IN, $in) || die "Couldn't open $in for input: $!";
open (OUT, "> $out") || die "Couldn't open $out for output: $!";
 
$ln = 1;    # first line number

while (<IN>)
{
  if(/\S+/ || $op eq "-a")
  {
    $_ = $ln . " " . $_;
    ++$ln;
  }
  print OUT $_;
}

close (OUT) || die "Can't close $out: $!";
close (IN)  || die "Can't close $in: $!";

Now change to the admin/root user on your Mac, make the file executable, and move the file to /usr/bin/nl, and switch back to being a regular user (you):

$ su
Password:
# chmod 755 nl
# mv nl /usr/bin/nl
# exit
$

To use the script, open a terminal, move into the directory containing the file you want to add line numbers to and invoke the script. For example to number a file on your desktop, you would type:

$ cd Desktop
$ nl sourcefilename destinationfilename

If you want all lines numbered, add the switch "-a" to the command:

$ nl -a sourcefilename destinationfilename

If you know how to do this in a bash shell script, I'd appreciate getting a copy!

Print plain