How to add line number in the command output or to a file in Linux ?
Suppose you want to add line numbers to the output of some command or when reading any file.
In this post we will look at a quick tip how to add such line numbers in front of the file/command output.
To achieve this, we can use several methods including awk command, sed utility or nl command.
Lets see each of these one by one.
Create a file and we add numbers while reading this file
### We have created a sample file named as newfile1 [root@ngelinux ~]# cat newfile1 dog cat lion yak bird [root@ngelinux ~]#
1. Using AWK command
### In awk we can print NR bultin to display the line number [root@ngelinux ~]# cat newfile1 | awk '{print NR ".", $0}' 1. dog 2. cat 3. lion 4. yak 5. bird [root@ngelinux ~]#
2. Using sed command
### "=" prints the line number ### And second sed command converts newline to "." [root@ngelinux ~]# cat newfile1 | sed '{=}' | sed 'N;s!\n!. !' 1. dog 2. cat 3. lion 4. yak 5. bird
3. Using nl command
nl command number lines of files and we can use “.” as separator using -s option.
### Using seperator as "." [root@ngelinux ~]# nl -s ". " newfile1 1. dog 2. cat 3. lion 4. yak 5. bird