How to Delete First/Last ‘n’ lines from command output in Shell?

Updated on July 18, 2018

One of my colleague came up with a query – How to Delete First/Last ‘n’ lines from the output of a command in Shell? For example, he wanted to trim down all the unnecessary lines from the output of a command – systemctl and print only the necessary lines. The command systemctl contained few generic lines at the end of the output as shown below. Well, he wants to remove those lines and print the rest.

Below is the command before trimming down the unnecessary lines.

$systemctl -a --type=service
 ......
 systemd-tmpfiles-setup.service loaded active exited Create Volatile Files and Directories
 systemd-udev-trigger.service loaded active exited udev Coldplug all Devices
 systemd-udevd.service loaded active running udev Kernel Device Manager
 systemd-update-done.service loaded active exited Update is Completed
 systemd-update-utmp-runlevel.service loaded inactive dead Update UTMP about System Runlevel Changes
 systemd-update-utmp.service loaded active exited Update UTMP about System Boot/Shutdown
 systemd-user-sessions.service loaded active exited Permit User Sessions
 systemd-vconsole-setup.service loaded active exited Setup Virtual Console
 tuned.service loaded active running Dynamic System Tuning Daemon

LOAD = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB = The low-level unit activation state, values depend on unit type.

92 loaded units listed.
To show all installed unit files use 'systemctl list-unit-files'.

In the above output, he wants to list only the services by removing the last 7 lines (space is also a line).

Solution: Use head command to remove the last 7 lines as shown below:

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

Note: the - symbol before 7, which is very important.

How to remove first n lines from the output of a shell command

To remove the first n lines from the output of a shell command use tail. Below example command removes the first 7 lines from the output of the shell command.

Note: the + symbol before 7, which is very important.

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

Was this article helpful?

Related Articles

Leave a Comment