Bash: How to Read File from Line X to End of File


Often you may want to use Bash to read a file starting from line X to the end of the file.

There are two common ways to do so:

Method 1: Use Pure Bash

tail -n +5 teams.txt

This particular example will return all lines from line number 5 to the end of the file for the file named teams.txt.

Method 2: Use sed

sed -n '5,$p' < teams.txt

This example will also return all lines from line number 5 to the end of the file for the file named teams.txt.

Note: The sed method tends to be faster when working with extremely large files.

The following examples show how to use each method in practice with the file named teams.txt, which contains the names of various basketball teams:

Let’s jump in!

Example 1: Use Pure Bash to Read from Line X to End of File

We can use the tail command with the following syntax to read all lines from line number 5 to the end of the file for the file named teams.txt:

tail -n +5 teams.txt

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

Bash read from line X to end of file

Notice that this returns all lines from the file named teams.txt ranging from line number 5 to the end of the file.

Note: Simply change the 5 to a different number to read the lines starting from a different line number.

Example 2: Use sed to Read from Line X to End of File

We can use the following syntax with sed to read all lines from line number 5 to the end of the file for the file named teams.txt:

sed -n '5,$p' < teams.txt

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

Bash use sed to read lines starting from specific line number to end of file

Notice that this returns all lines from the file named teams.txt ranging from line number 5 to the end of the file.

Note: The syntax 5,$ is used to specify a range from line 5 to the last line ($) in the file and we use the p command to print these lines.

Related Tutorials

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

Bash: How to Count Number of Blank Lines in File
Bash: How to Delete Duplicate Lines in File
Bash: How to Count Number of Unique Lines in File

Leave a Reply