View the start/end of a file linux

来源:互联网 发布:c汉诺塔循环算法 编辑:程序博客网 时间:2024/05/06 05:10

tail - lets you view the LAST 10 lines in a file

head - shows you the FIRST 10 lines in a file by default


Introduction

There are two very useful commands in Linux which let you see part of a file. The first is called head and by default it shows you the first 10 lines in a file. The second is the tail command which by default lets you view the last 10 lines in a file.

Imagine the file you are reading has 300,000 lines in it. Imagine also that the file consumes a lot of disk space.

A common use for the head command is to make sure that the file you want to view is indeed the correct file. 

You can usually tell if you are looking at the correct file just by seeing the first few lines.

The tail command is useful for viewing the last few lines of files and is very good when you want to see what is happening in a log file held in the /var/log folder.


How To Specify The Number Of Lines To Show

Maybe you want to see more than the last 10 lines of the file. You can specify the number of lines you want to see using the following command:

sudo tail -n20 <filename>

The above example would show the last 20 lines of the file.

Perhaps you know the first 30 rows in a file are comments and you just want to see the data within a file. In this case you would use the following command:

sudo tail -n+20 <filename>

The tail command is often use alongside the more command so that you can read the file a page at a time.

For example:

sudo tail -n+20 <filename> | more

The above command sends the last 20 lines from filename and pipes it as the input to the more command:

You can also use the tail command to show a certain number of bytes instead of lines:

sudo tail -c20 <filename>

Again you can use the same switch to start showing from a certain byte number as follows:

sudo tail -c+20 <filename>




How To Monitor A Log FIle

There are many scripts and programs that don't output to the screen but do append to a log file as they are running.

In this instance you might want to monitor the log file as it changes. You can use the following tail command to check how the log changes every so many seconds:

sudo tail -F -s20 <filename>

You can also use tail to continue monitoring a log until a process dies as follows:

sudo tail -F --pid=1234 <filename>

To find the process id for a process you can use the following command:

ps -ef | grep <programname>

For example imagine you are editing a file using nano. You can find the process ID for nano using the following command:

ps -ef | grep nano

The output from the command will give you a process ID. Imagine the process ID is 1234.

You can now run tail against the file being edited by nano using the following command:

sudo tail -F --pid=1234 <filename>

Every time the file is saved within nano the tail command will pick up the new lines at the bottom. The command only stops when the nano editor is closed.






0 0
原创粉丝点击