Sponsored Links

5 ways to display line numbers in a file

In this article, we will see some different command methods with which we can display the file contents with its line number.

Let’s use the following file as example:
open source
ubuntu canonical
linux mint
debian fedora

Here are the methods we can use to get the line numbers before each line.

1. Use nl

nl (number lines) is a linux command whose purpose is to do line numbering. This command is very rarely known or used though. To get the line numbers before each row using nl, just run:

nl file

2. Use cat with ‘-n’

‘-n’ or ‘–number’ is the option of cat to number all output lines. This is the second simplest command to get the line numbers:
cat -n file

3. Use awk

awk has a special variable, NR, to do this task. NR contains the line number of the line being processed by awk currently.
awk ‘{print NR, $0}’ file

4. Use perl

When awk has NR, perl has the similar variable $, which gives line number at any point of a file.

perl -ne ‘{print $.,” “, $_}’ file

5. Use sed

You can use sed in a complex way to do the task. First, we will need to give each line a number by using the ‘=’ operator. But when using ‘=’, the text content will drop down to the next line so we need to join the text content and the line number, and here the ‘N’ function of sed can be used. Using ‘N’, we substitute the new line character by 2 spaces. Here is the final command with sed:

sed ‘=’ file | sed ‘N;s/n/ /’

Read more …

Comments are closed.