I know I have already asked this question, but I didn't get an answer that worked. So please could someone answer my question?

I have a text file, containing paragraphs of text, each separated by a single empty line. Now I need to number each paragraph with its own number. So the first paragraph will have the number 1 in the margin, the second paragraph will have the number 2 in the margin and the third will have the number 3 in the margin, etc. I know it seems obvious but I think my last post may not have got the message across clearly.

So I need a Linux command that can get that job done. However, my issue is that the command needs to be simple. By that, I mean no complicated Perl scripts or, any difficult to understand, blocks of code.

What I'm looking for, is a simple command that can easily carry out the task. Or if a script needs to be written, make it simple and explain the code so someone who has never used Perl nor Bash scripts can still apply it to their code and understand what they are doing.

Sorry if the question may come across as impolite. Responses will much be appreciated because there is nothing on the web on this topic.

  • What do you mean by margin? Feb 25 '16 at 16:20
  • next to the text
    – Inquirer
    Feb 25 '16 at 16:21
  • 1
    Try awk '{printf "%4s║%s\n",NF?(b=0)+a++?"":n+1:(b++||a=0*n++)?"":"",$0}' your-file Feb 25 '16 at 16:50
  • Or awk '{printf "\33[32m%4s║\33[m%s\n",NF?(b=0)+a++?"":n+1:(b++||a=0*n++)?"":"",$0}' you-file if you like colours Feb 25 '16 at 16:54

All obtained from https://superuser.com/a/916248/151431

You can use perl

$ perl -00pe 's/^/$./' file
  • -00 turns on paragraph mode where "lines" are defined by consecutive \n\n.
  • -p tells perl to print each line of the input file after running the script given by -e on it.
  • s/^/$./ will replace the start of the line (^) with the current "line" (paragraph) number $.

You can use awk

$ awk -v RS='\n\n' -vORS='\n\n' '{print NR$0}' file | head -n -2 
  • -v RS='\n\n' sets awk's record separator to consecutive newline characters. Like perl's paragraph mode, this makes it treat paragraphs as "lines". We then tell it to print the current line number (NR) and the current "line" $0.
  • -vORS= sets the output record separator to consecutive newlines so that paragraphs are separated by blank lines in the output as well.
  • head -n -2 to avoid the add of two empty lines at the end of the output.

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