In this post we are going to discuss – How to use head and tail Command in Linux
The head command is used to output a subset of lines from the file starting from the top. By default it will output the first 10 lines.
will display the first 10 lines of the file “grepfile”. So make sure you have more than 10 lines in your file to understand the working of head command.
-c: option prints first few bytes of the file. For example:
prints the first 10 characters from the file “grepfile”.
The same option can also be used to print all but the last few characters. For example suppose you want to print all the file content except for the last 10 characters.
All the contents are printed except for the last 10 characters. The result can be compared with the output of cat command which shows the entire content of the file.
-n: prints the first n lines instead of 10. For example,
prints the first two lines of the file “grepfile”
The tail command is used to output a subset of lines of a file from the bottom. By default it prints the last 10 lines
will display the last 10 lines of the file “grepfile”. So make sure you have more than 10 lines in your file to understand the working of tail command.
-c: option prints last few bytes of the file. For example:
$tail -c 10 grepfile
will print the last 10 characters of the file “grepfile”
-n: prints the last n lines instead of 10. For example,
$tail -n 5 grepfile
will print the last 5 lines of the file “grepfile”
-f: This option allows you see the contents being added at real time. Open two terminals. In terminal 1 type the command
$tail -f f1.txt
where f1.txt is a file having some content. Now you will see the last few lines of the file but the control will not come back to command prompt
Now, in second another terminal type the command
write some content
You see that in the first terminal this new line “write some content” is added to the output. So, as you keep on appending content to the file it will come up in the output of tail -f command
Q1. How to display the lines starting from the 5 line?
Q2. How can you view all the contents of a file except the last 5 characters