I want to print a text file in terminal with numbered paragraphs using the cat command.

  • cat -n ? man cat ? – Archemar Oct 12 '16 at 13:18
  • cat -n numbers every line, i only want each paragraph to be numbered e.g 1.(text) – LinuxMaster2000 Oct 12 '16 at 13:19
  • 3
    Who is this person that keeps assigning this idiotic assignment to their students? You must be the 20th unfortunate user who has tried to deal with this. it is not possible without editing the source of cat. Please tell your teacher to come and ask here so we can set them straight. – terdon Oct 12 '16 at 14:50
  • @terdon: That should be an answer, IMO. – Oskar Skog Mar 8 '17 at 8:48

While some cat implementations have a -n option to number lines or -b to number non-blank lines, I'm not aware of any that has an option to number paragraphs. You'd need another tool like awk to do that:

number_paragraphs() {
  awk '!/[^[:blank:]]/ {print; flag=0; next}
       !flag++ {n++}
       {printf "%4d %s\n", n, $0}'

to get an output like:

$ lorem -p2 | fmt -w70 | number_paragraphs
   1 Aspernatur dicta in commodi suscipit officia. Est at voluptas aut
   1 eveniet. Voluptatem placeat recusandae sed consequatur et ullam
   1 expedita vitae. Quis velit modi soluta ea eos eaque cum inventore.

   2 Tenetur ipsam non commodi. At aut aut quaerat. Delectus ipsam
   2 dicta corrupti consequuntur. Suscipit et quibusdam nihil suscipit
   2 consequuntur. Quis eum numquam qui.


number_paragraphs() {
  awk '!/[^[:blank:]]/ {print; flag=0; next}
       !flag++ {n++; printf "%4d %s\n", n, $0; next}
       {print "    ", $0}'

to get an output like:

$ lorem -p2 | fmt -w70 | number_paragraphs
   1 Officia a adipisci accusantium dolores velit. Et fugiat
     exercitationem quibusdam. Neque nihil explicabo molestiae sapiente

   2 Ipsa error ad nobis reprehenderit. Eius adipisci similique nemo
     culpa qui quos voluptatem. Ut sint consectetur unde voluptatibus
     mollitia. Recusandae natus et quasi et perferendis. Accusantium
     non qui et iste fugiat sit unde dolores.

Simple, you don't.

cat(1) only concatenates the files given as arguments, so there is no way to make cat(1) automatically write out numbers right in the middle of a file.

  • Create a script that reads from stdin and writes to stdout and does what you want it to do. And abuse cat(1) to read the file and pipe it to your script. That way you will be (ab)using cat(1). – Oskar Skog Oct 12 '16 at 13:23
  • Sorry, I tried to add a newline to the comment, so I had to edit. – Oskar Skog Oct 12 '16 at 13:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.