Bash: How to Print Specific Range of Lines from File


Often you may want to use Bash to print a specific range of lines from a file.

You can use the following basic syntax to do so:

sed -n '3,7p;8q' teams.txt > teams_new.txt

This particular example prints the text from lines 3 through 7 of the file named teams.txt and saves the results to a new file named teams_new.txt.

Here is what the various sed commands do:

  • -n: Prevent echoing the input as output
  • 3,7p: “Print” lines 3 through 7 in the file
  • 8q: “Quit” processing once line 8 is reached
  • >: Specifies that the output should be saved to a new file

Note that by using 8q we are able to tell sed to stop processing the file completely once it reaches line 8.

Without using this command, sed would continue to process the rest of the file. If you’re working with a large file, this could be time-consuming.

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

Example: How to Print Range of Lines from File in Bash

Suppose that we have a file in our current directory named teams.txt that contains the names of various basketball teams.

We can use the cat command to view the contents of this file:

Suppose that we would like to print only the team names on lines 3 through 7.

We can use the following syntax to do so:

sed -n '3,7p;8q' teams.txt > teams_new.txt

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

Bash print range of lines from file

Notice that when we use the cat command to view the contents of the teams_new.txt file we can see that it contains only the team names from lines 3 through 7 from the original file.

Feel free to replace 3 and 7 with the specific range of lines that you’d like to print from your own file.

Related Tutorials

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

Bash: How to Sort a File by Line Length
Bash: How to Print the Longest Line in a File
Bash: How to Split File into Multiple Files Based on Column Value

Leave a Reply