Tail command in linux/Unix

Tail command in linux/Unix

Tail command prints N number of lines from a file. By default tail command will print the last 10 lines of a file. Tail command is a text processing commands. Using tail command last N lines can be viewed. Previously we have studied about head command. By combining both head and tail command we can achieve multiple text processing task.

Tail command in linux/Unix

How to use tail command

#tail /etc/passwd

The above tail command will display last 10 lines of the file /etc/passwd

How to view last 20 lines of a file

#tail -n 20 /etc/passwd

or

#cat -n /etc/passwd | tail -n 20

The above command will display last 20 lines of the file /etc/passwd

Tail command in linux/Unix

Option:

-n — Prints the first N numbers. If 30 mentioned instead of n, then first 30 lines of a file will be printed

How to view last 30 lines of a file using tail command

#cat -n /etc/passwd | tail -30

Another Method

#tail -30 /etc/passwd

Interview Question:

There are total of 123 lines in a file. How to view only the line from 50 to 70

#cat -n /etc/passwd | head -n 70 | tail -n 20

Tail command in linux/Unix

The above command will only print line from number 50 to 70. How the command works, First of all cat command will display the whole /etc/passwd file content with line numbers. Then the standard output of the command is passed to input for head command. Then head command display top 70 lines of the file /etc/passwd. Again the standard output of the head command is passed to standard input to the tail command. Then tail command displays the last 20 lines of the file. The last 20 lines is from 50 to 70. That’s it

Hope you got some useful information




Leave a Reply

Your email address will not be published. Required fields are marked *