How to view only first or last few lines in linux ?
In the previous post we saw how to view / display the contents of a text file with more and less commands. What if you don't want to view the entire file contents? Say, you want to view only the first 10 lines of the file. Or you want to see only last few lines of the file. For that purpose we use the commands head and tail.
Syntax:
head
head is Unix/*nix command used to display the beginning of a text file or a piped data.Syntax:
head filename
head README.txt
By default head will display the first 10 lines of a file. Instead to view the first 20 lines of the README.txt file, type
head -n 20 README.txt
Like files, head can be used along with pipes also. For example to find the first 3 files with highest file size in a directory, type
ls -S|head -n 3
tail
tail command is the opposite of head
command. i.e By default tail command will display the last 10 lines of
file or a piped data.
Syntax:
tail filename
tail README.txt
tail README.txt
To view the last 20 lines of the file, type
tail -n 20 README.txt
tail can be used along with pipes also. For example to find 3 files with smallest file size in a directory, type
ls -S|tail -n 3
One of the most used command line option of tail command is -f (follow). tail used with -f will output appended data as the file grows. Take the case of a busy web server. The server's access_log will log the details like the ip address of the client machine, date and time of the access, page accessed, band width utilized, http response code etc whenever a person accesses the server. So the log is growing continuously as new data is appended to the file. To view the details in realtime, type
tail -f /path/to/access_log
Comments
Post a Comment