Subject: RE: bug#14505: Bug in "cat" command

From: "Kakkar, Mayank (NSN - IN/Bangalore)" <[email-masked]>
Date: Thu, 30 May 2013 05:19:40 +0000

Hi Bob,

Thanks. That was very informative. 

Is http://www.proulx.com/~bob/ your site ? Quite interesting ... :) 

Regards
Mayank

-----Original Message-----
From: ext Bob Proulx [mailto:[email-masked]] 
Sent: Thursday, May 30, 2013 10:41 AM
To: Kakkar, Mayank (NSN - IN/Bangalore)
Cc: [email-masked]
Subject: Re: bug#14505: Bug in "cat" command

Kakkar, Mayank (NSN - IN/Bangalore) wrote:
> I am referring to the manual -> 'Sams teach yourself shell in 24
> hours', which is authored by Sriranga Veeraraghavan.

It isn't unusual for books to have bugs too.

> Following is example potrayed in that manual:
> 
> If multiple files are specified, the contents of the files are
> concatenated in the output, but line numbering is restarted at 1 for
> each file. As an illustration, the following command,
> 
> $ cat -b fruits users
> 
> produces the output
> 
> 1 Fruit Price/lbs Quantity
> 2 Banana $0.89 100
> 3 Peach $0.79 65
> 4 Kiwi $1.50 22
> 5 Pineapple $1.29 35
> 6 Apple $0.99 78
> 
> 1 ranga
> 2 vathsa
> 3 amma

That doesn't make sense because there is a blank line in the middle.
I think the book has an incorrect example.

> So, this was what led me think this is a bug in cat command for RHEL
> 5.7, because this guy must have experimented it on the RHEL machine
> before printing it in the manual.

The GNU cat documentation says:

  `-b'
  `--number-nonblank'
     Number all nonempty output lines, starting with 1.

Which talks about *output* lines not input lines.  Since cat is
conCATenating lines and emitting them to the output the output lines
are the ones that would be numbered.

If you really want to renumber each file then you can use a for loop.

  for f in fruits users; do
    cat -b "$f"
  done

But actually cat should never have added line numbering.  It
violates the principle that tools should be simple and do one thing
and do it well.  So it is sad that cat now has line numbering.  That
is just a bad thing.

Instead for line numbering I would use "nl".

  http://pubs.opengroup.org/onlinepubs/009695399/utilities/nl.html

Or I more likely for me I would use awk since it is standard and has
all of the needed functionality.  To do what you want, restarting
numbering for each file:

  $ awk '{print FNR, $0 }' fruits users

Or to do what nl (and cat too) does:

  $ awk '{print NR, $0 }' fruits users

Bob