How to Use sed to Print Out Line Numbers


Often you may want to use sed to print out line numbers for each line in a file.

You can use the following basic syntax to do so:

sed '!d;=' cities.txt | paste -d: - -

This particular example will print each line in the file named cities.txt with the line number printed in front of each line with a colon.

Note that you can also use the following syntax to only print the lines in a specific range of the file:

sed '2,4!d;=' cities.txt | paste -d: - -

This particular example will print line numbers 2 through 4 in the file named cities.txt with the line number printed in front of each line with a colon.

The following example shows how to use this syntax in practice.

Example: How to Use sed to Print Out Line Numbers

Suppose we have a file named cities.txt that contains the names of various U.S. cities:

Suppose that we would like to print the text from the file with the line number at the beginning of each line.

We can use the following syntax to do so:

sed '!d;=' cities.txt | paste -d: - -

The following screenshot shows how to use this syntax in practice:

sed print out line numbers

Notice that this returns each line from the file with the line number and a colon printed before it.

Note that we could also use the following syntax to only print the line numbers 2 through 4:

sed '2,4!d;=' cities.txt | paste -d: - -

The following screenshot shows how to use this syntax in practice:

sed print line numbers of specific range

Notice that this returns each line in the range 2 through 4 with the line number and a colon printed before it.

Note: Feel free to replace the colon ( : ) with a different symbol if you would like to use a different symbol to separate the line number and the content of the line itself.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Insert Line at Specific Line Number
How to Use sed to Replace All Text After Match
How to Use sed to Replace All Text Before Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply