[Linux]: How to print First/Last n lines from the output of a shell command

Updated on September 5, 2023

While developing a monitoring tool, one of my colleague came up with the above question. He wanted to print the first n lines or last n lines output of the below command:

$ systemctl -a --type=service

How to print First n lines from the output of a shell command

To print the first n lines from the output of a shell command use the below command using head. Below example command prints the first 7 lines from the output of the shell command.

$ systemctl -a --type=service | head -n 7

How to print Last n lines from the output of a shell command

To print the last n lines from the output of a shell command use the below command using tail. Below example command prints the first 7 lines from the output of the shell command.

$ systemctl -a --type=service | tail -n 7

Was this article helpful?

Related Articles

Leave a Comment