How to add line number at the beginning of each line

There are many ways to do this, I will try to show some

Sample file ‘/tmp/file’
Apple
Apricot
Avocado
Banana
Bilberry
Blackberry
Blackcurrant

Method 1

Using ‘nl’
# nl /tmp/file
     1  Apple
     2  Apricot
     3  Avocado
     4  Banana
     5  Bilberry
     6  Blackberry
     7  Blackcurrant
Add a symbol after the numbers

# nl -s “. ” /tmp/file
     1. Apple
     2. Apricot
     3. Avocado
     4. Banana
     5. Bilberry
     6. Blackberry
     7. Blackcurrant
Save the output to a file
# nl -s “. ” /tmp/file  > /tmp/newfile

Method 2

Using ‘perl’
#  perl -pe ‘printf “%u. “, $.’ /tmp/file
1. Apple
2. Apricot
3. Avocado
4. Banana
5. Bilberry
6. Blackberry
7. Blackcurrant

Method 3

Using ‘awk’
# awk ‘{printf “%d. %sn”, NR, $0}’ /tmp/file
1. Apple
2. Apricot
3. Avocado
4. Banana
5. Bilberry
6. Blackberry
7. Blackcurrant

# awk ‘{print NR”.”,$0}’ /tmp/file
1. Apple
2. Apricot
3. Avocado
4. Banana
5. Bilberry
6. Blackberry
7. Blackcurrant

Method 4

Using ‘sed’
# sed ‘=’ /tmp/file | sed ‘{N;s/n/. /}’
1. Apple
2. Apricot
3. Avocado
4. Banana
5. Bilberry
6. Blackberry
7. Blackcurrant

Leave a Comment