How to Use sed to Print Specific Lines in File


Often you may want to use sed to print out specific lines from a file.

You can use the following methods to do so:

Method 1: Print One Specific Line from File

sed -n '4p' cities.txt

This particular example will print line number 4 from the file named cities.txt.

Method 2: Print Multiple Specific Lines from File

sed -n '4p;7p' cities.txt

This particular example will print line numbers 4 and 7 from the file named cities.txt.

Method 3: Print Range of Lines from File

sed -n '4,7p' cities.txt

This particular example will print line numbers 4 through 7 from the file named cities.txt.

The following example shows how to use each of these methods in practice with a file named cities.txt that contains the names of various U.S. cities:

Example 1: Print One Specific Line from File

Suppose that we would like to print only line number 4 from the cities.txt file.

We can use the following syntax to do so:

sed -n '4p' cities.txt 

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

sed print one specific line from file

Notice that this prints only line number 4 from the cities.txt file.

Example 2: Print Multiple Specific Lines from File

Suppose that we would like to print only line numbers 4 and 7 from the cities.txt file.

We can use the following syntax to do so:

sed -n '4p;7p' cities.txt

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

sed print multiple specific lines from file

Notice that this prints only line numbers 4 and 7 from the cities.txt file.

Example 3: Print Range of Lines from File

Suppose that we would like to print line numbers 4 through 7 from the cities.txt file.

We can use the following syntax to do so:

sed -n '4,7p' cities.txt

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

sed print range of lines from file

Notice that this prints line numbers 4 through 7 from the cities.txt file.

Related Tutorials

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

How to Use sed to Print Out Line Numbers
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply