Search code examples
line-numbers

how to repeat line numbers in a file separated by an empty line


I want to restart the counting with 1 where ever there is an emptyline in my file.

My file is like this: cat test.txt

333|111|222|333| 222|111|333|222|

I am using cat test.txt | sed 's/|/\n/g' | nl output: 1 333 2 111 3 222 4 333

5 222 6 111 7 333

What i want is that after empty line the counting again start from 1. desired output: 1 333 2 111 3 222 4 333

1 222 2 111 3 333

please help?


Solution

  • This task is quite trivial in 'awk', or one of its clones gawk, nawk.

    Create a script linerecount.awk with content:

    /^$/ { lineno=0; next}
         { print ++lineno, $0}
    

    First line obviously resets the linenumber and skips to next line. Second line increments linenumber, prints it, prints line.

    Apply with gawk -f linerecount.awk to whatever you want.

    Input:

    $ cat input.txt
    First line
    Second line
    Third line
    
    Second part, First line
    Second line
    Third line
    
    Final part, First line
    Second line
    

    Output:

    $ gawk -f linerecount.awk < input.txt
    1 First line
    2 Second line
    3 Third line
    1 Second part, First line
    2 Second line
    3 Third line
    1 Final part, First line
    2 Second line