Search code examples
awkgawk

awk numbering all lines in each paragraph, increasing by one for each paragraph


start with number 1 how to add that same number and a space in front of every line in one paragraph, same for number 2 and the next paragraph. Paragraphs are separated by a blank line, about 50 paragraphs in the text file, each paragraph has 2 to 30 lines.

some text here
more numbers and text

more text here
and here is more text
number text

1 some text here
1 more numbers and text

2 more text here
2 and here is more text
2 number text


Solution

  • The trick here is to view the paragraphs as records, and the lines as fields.

    awk 'BEGIN { RS="\n\n"; FS="\n" }
         { for (i = 1; i <= NF; i++)
             print FNR, $i;
           print "" }' < in > out
    

    Happy New Year!