Search code examples
bashrow-number

Add numbers to the beginning of every line in a file


How can I add numbers to the beginning of every line in a file?

E.g.:

This is
the text
from the file.

Becomes:

000000001 This is
000000002 the text
000000003 from the file.

Solution

  • AWK's printf, NR and $0 make it easy to have precise and flexible control over the formatting:

    ~ $ awk '{printf("%010d %s\n", NR, $0)}' example.txt
    0000000001 This is
    0000000002 the text
    0000000003 from the file.