Friday, 2 August 2019

Linux - head & tail

Linux head and tail commands practical examples and explanation

Similar to cat command, Head and tail commands deal with displaying the content of a file. But they don’t display the entire content of it, instead show a certain number of lines of the file from head & tail part.
In this section, we will see some of the examples for head command and tail command individually.

Let’s start with head command,
Syntax:
head filename
head -n12 file-name

By default, the head command will show top 10 lines of a file.

Example-1:
Show top lines of a file:
We have a file abclearn_lab4 and to look at its top 10 lines.
[rreddy@abclearn abclearn_dir1]$ head abclearn_lab4.txt
this line should replace the existing one
this is the first line in new file
Hi
this information saves in a new file
Hey, this goes into a file
This is another test line
Testing
Success one
0121313121
New line content

To see top 4 lines of a file,
[rreddy@abclearn abclearn_dir1]$ head -n 4 abclearn_lab4.txt
this line should replace the existing one
this is the first line in new file
Hi
this information saves in a new file

Between -n and 4 you can keep the space or remove it. It works in both ways.
head -n4 abclearn_lab4.txt

Practical usage:
The tail command will show the number of lines from the bottom of the file.
Syntax:
tail filename
tail -n number-of-lines file-name

Example-1:
Show bottom lines of a file:
Similar to head command it shows bottom 10 lines of a file by default.
[rreddy@abclearn abclearn_dir1]$ tail abclearn_lab4.txt
How are you
closing this file here
Test line
Test line
Test line
Test line
Test line
Test line
Test line

If we want to see only last 3 lines of a file abclearn_lab4.txt
[rreddy@abclearn abclearn_dir1]$ tail -n 3 abclearn_lab4.txt
How are you

closing this file here.
Note: 
head and tail commands will display even empty lines as part of the output.

Exampe-2:
To see continuous updates of a file:
The tail command has a wonderful feature to show, continuous updates of a file to the bottom of the page.
We can use “-f” option with tail command,
Syntax:
tail -f file-name

[rreddy@abclearn abclearn_dir1]$ tail -f errorfile


Practical usage:
Assume we have a log file and want to observe the content updated dynamically.

Let’s take a file, which is having some 90 lines in it. And I want to display lines from line number 20 to 35. How can we do it?
We can use the combination of head and tail commands to display the output.
[rreddy@abclearn abclearn_dir1]$ head -n35 filename | tail -n15

0 comments:

Post a Comment