Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 
like image 404
Village Avatar asked Nov 21 '11 01:11

Village


People also ask

How do I add line numbers to a 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.


2 Answers

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 ;-)

like image 178
tamasgal Avatar answered Sep 18 '22 07:09

tamasgal


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. 
like image 39
Raymond Hettinger Avatar answered Sep 21 '22 07:09

Raymond Hettinger