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.
Method 1 - Using 'nl' command The "nl" command is dedicated for adding line numbers to a file. It writes the given file to standard output, with line numbers added.
Don't use cat or any other tool which is not designed to do that. Use the program:
nl - number lines of files
Example:
$ nl --number-format=rz --number-width=9 foobar $ nl -n rz -w 9 foobar # short-hand
Because nl is made for it ;-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With