I want to print a text file in terminal with numbered paragraphs using the cat command.
Asked
Active
Viewed 428 times
0
-
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
-
3Who 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 08 '17 at 08:48
2 Answers
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.
Stéphane Chazelas
- 522,931
- 91
- 1,010
- 1,501
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.
Oskar Skog
- 377
- 1
- 3
- 13
-
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
-