0

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

2 Answers2

2

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.

Or:

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

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

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