Add numbers to the beginning of every line in a file

BashRow Number

Bash Problem Overview


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.

Bash Solutions


Solution 1 - Bash

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

Solution 2 - Bash

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.

Solution 3 - Bash

You're looking for the nl(1) command:

$ nl -nrz -w9  /etc/passwd
000000001	root:x:0:0:root:/root:/bin/bash
000000002	daemon:x:1:1:daemon:/usr/sbin:/bin/sh
000000003	bin:x:2:2:bin:/bin:/bin/sh
...

-w9 asks for numbers nine digits long; -nrz asks for the numbers to be formatted right-justified with zero padding.

Solution 4 - Bash

cat -n thefile will do the job, albeit with the numbers in a slightly different format.

Solution 5 - Bash

Easiest, simplest option is

awk '{print NR,$0}' file

See comment above on why nl isn't really the best option.

Solution 6 - Bash

Here's a bash script that will do this also:

#!/bin/bash
counter=0
filename=$1
while read -r line
do
  printf "%010d %s" $counter $line
  let counter=$counter+1
done < "$filename"

Solution 7 - Bash

perl -pe 'printf "%09u ", $.' -- example.txt

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVillageView Question on Stackoverflow
Solution 1 - BashtamasgalView Answer on Stackoverflow
Solution 2 - BashRaymond HettingerView Answer on Stackoverflow
Solution 3 - BashsarnoldView Answer on Stackoverflow
Solution 4 - Bashuser149341View Answer on Stackoverflow
Solution 5 - BashegorulzView Answer on Stackoverflow
Solution 6 - BashslashdottirView Answer on Stackoverflow
Solution 7 - BashPeter John AcklamView Answer on Stackoverflow