Linux показать последние 100 строк файла

Linux Tail Command

The tail command displays the last part (10 lines by default) of one or more files or piped data. It can be also used to monitor the file changes in real time.

One of the most common uses of the tail command is to watch and analyze logs and other files that change over time, usually combined with other tools like grep .

In this tutorial, we will show you how to use the Linux tail command through practical examples and detailed explanations of the most common tail options.

Tail Command Syntax #

Before going into how to use the tail command, let’s start by reviewing the basic syntax.

The tail command expressions take the following form:

  • OPTION — tail options . We will go over the most common options in the next sections.
  • FILE — Zero or more input file names. If no FILE is specified, or when FILE is — , tail will read the standard input.

How to Use the Tail Command #

In its simplest form when used without any option, the tail command will display the last 10 lines.

How to Display a Specific Number of Lines #

Use the -n ( —lines ) option to specify the number of lines to be shown:

You can also omit the letter n and use just the hyphen ( — ) and the number (with no space between them).

To display the last 50 lines of a file named filename.txt you would use:

The following example will display the same result as the above commands:

How to Display a Specific Number of Bytes #

To show a specific number of bytes use the -c ( —bytes ) option.

For example to display the last 500 bytes of data from the file named filename.txt you would use:

You can also use a multiplier suffix after the number to specify the number of bytes to be shown. b multiplies it by 512, kB multiplies it by 1000, K multiplies it by 1024, MB multiplies it by 1000000, M multiplies it by 1048576, and so on.

The following command will display the last two kilobytes (2048) of the file filename.txt :

Читайте также:  My conf linux ubuntu

How to Watch a File for Changes #

To monitor a file for changes use the -f ( —follow ) option:

This option is particularly useful for monitoring log files. For example, to display the last 10 lines of the /var/log/nginx/error.log file, and monitor the file for updates you would use:

tail -f /var/log/nginx/error.log

To interrupt the tail command while it is watching a file, press Ctrl+C .

To keep monitoring the file when it is recreated, use the -F option.

This option is useful in situations when the tail command is following a log file that rotates. When used with -F option the tail command will reopen the file the as soon as it became available again.

How to Display Multiple Files #

If multiple files are provided as input to the tail command, it will display the last ten lines from each file.

tail filename1.txt filename2.txt

You can use the same options as when displaying a single file.

This example shows the last 20 lines of the files filename1.txt and filename2.txt :

tail -n 20 filename1.txt filename2.txt

How to Use Tail with Other Commands #

The tail command can be used in combination with other commands by redirecting the standard output from/to other utilities using pipes.

For example to monitor the apache access log file and only display those lines that contain the IP address 192.168.42.12 you would use:

tail -f /var/log/apache2/access.log | grep 192.168.42.12

The following ps command will display the top ten running processes sorted by CPU usage:

ps aux | sort -nk +3 | tail -5

Conclusion #

By now you should have a good understanding of how to use the Linux tail command. It is complementary to the head command which prints the first lines of a file to the to the terminal.

Источник

Команда tail

Печатает последние 10 строк файла или последние 10 строк вывода другой команды. Количество печатаемых строк можно изменить. Поддерживает отслеживание изменения содержимого файла.

Синтаксис

ФАЙЛ — это один или несколько файлов, записанных через через пробел, строки которых необходимо вывести.

Если указывается несколько файлов, то выводится последние N строк из каждого файла. Перед началом вывода строк каждого файла выводится имя файла.

Опции

Задает количество строк, которое необходимо вывести.
LINES — количество первых строк из файла, которое нужно вывести.
Если перед LINES указан знак + , то выводится все содержимое файла, кроме первых N-1 строк (где N= LINES ), то есть начиная со строки с номером N.

Задает количество байт, которое необходимо вывести.
BYTES — количество последних байт из файла, которое нужно вывести.
Если перед значением BYTES указан знак + , то выводится все содержимое файла, кроме первых N-1 байт (где N= BYTES ), то есть начиная с байта с номером N.

Читайте также:  Linux настроить сеть через терминал

Значение BYTES можно указать с суффиксом: b (512 байт), kB (1000 байт), MB (1000*1000), M (1024*1024), GB (1000*1000*1000), G (1024*1024*1024), T, P, E, Z, Y.
Также можно использовать двоичные приставки: KiB=K, MiB=M и так далее.

Отслеживать появление новых строк в файле. Выводить последние строки файла по мере их появления.
По умолчанию tails следит за дескриптором файла (—follow=descriptor), то есть, например, если во время отслеживания файл будет переименован, то это не повлияет на выполнение команды.

Пытаться открыть файл, если он недоступен. Опция используется только при отслеживании файла, то есть совместно с опцией -f или —follow=
Опцию удобно использовать при отслеживании файлов логов, которые могут ротироваться, то есть отслеживаемый файл периодически может быть недоступен.

То же самое, что и —follow=name —retry. Отслеживать файл по имени; пытаться открыть, если недоступен.

Используется совместно с опцией —follow=name. Повторно открывает файл, размер которого не изменился после N проверок (по умолчанию 5), чтобы проверить был ли файл переименован (например, это ротируемый файл логов) или выполнен unlink.

Прекратить отслеживание, если процесс с идентификатором PID умирает. Используется совместно с опцией -f.

Делать паузу примерно N секунд (по умолчанию 1) между проверками файла. Используется совместно с опцией -f. При inotify и —pid=PID выполнять проверку процесса PID минимум один раз в N секунд.

Не печатать имена файлов.
Примечание: Имена файлов печатаются, если указано несколько файлов. Если данная опция установлена, то имена файлов не печатаются, и между содержимым разных файлов не добавляется пустая строка.

Примеры использования команды tail

Рассмотрим несколько примеров использования команды tail в Linux.

Вывод последних строк файла на экран

Вывести последние 10 строк файла:

Вывести последние 25 строк файла:

Вывод нескольких последних байт файла

Вывести содержимое последних 100 байт файла:

Вывести содержимое последнего мегабайта файла (здесь используется суффикс M):

Вывод последних строк из нескольких файлов

Вывести последние 3 строки из каждого файла:

tail -n3 myfile.txt myfile2.txt

Использование tail для печати последних строк вывода другой команды

Команду tail можно использовать для того, чтобы напечатать последние N строк вывода другой команды.

Выполнить команду ls -t и вывести только последние 5 строк. Команда ls -t выводит на экран список файлов в директории и сортирует их по времени изменения (так как указан ключ -t). В данном примере будут выведены не все файлы, а только последние 5.

Вывести содержимое файла командой cat, но напечатать только последние 12 строк:

cat /var/log/Xorg.0.log | tail -n12

Отслеживание изменений в файлах логов

Команда tail может использоваться для отслеживания изменений в файлах логов (или любых других), в которые периодически могут добавляться новые строки.

Отслеживать появление новых строк в файле /var/log/messages и выводить последние 20 строк файла:

tail -n20 -F /var/log/messages

Предыдущая команда имеет особенность, заключающуюся в том, что, например, если во время отслеживания файл будет очищен или заменен другим файлом, то после этого команда tail напечатает все содержимое файла. Если такое поведение неприемлемо, то можно воспользоваться командой watch совместно с tail. Выводить последние 20 строк файла раз в 2 секунды:

watch -n2 tail -n20 myfile.txt

Источник

Читайте также:  Linux no volume group found

Linux tail command

Computer Hope

On Unix-like operating systems, the tail command reads a file, and outputs the last part of it (the «tail»).

The tail command can also monitor data streams and open files, displaying new information as it is written. For example, it’s a useful way to monitor the newest events in a system log in real time.

This page covers the GNU/Linux version of tail.

Description

By default, tail prints the last 10 lines of each file to standard output. If you specify more than one file, each set of output is prefixed with a header showing the file name.

If no file is specified, or if file is a dash (««), tail reads from standard input.

Syntax

tail [-c |--bytes=>num] [-f] [--follow[=name|descriptor>]] [-F] [-n |--lines=>num] [--max-unchanged-stats[=num]] [--pid=pid] [-p|--quiet|--silent>] [--retry] [-s |--sleep-interval=>num] [-v|--verbose>] [file . ]

Options

Option Description
-c [+]num,
—bytes=[+]num
Output the last num bytes of each file.

You can also use a plus sign before num to output everything starting at byte num. For instance, -c +1 prints everything.

If you follow more than one file, a header will be printed to indicate which file’s data is being printed.

If the file shrinks instead of grows, tail lets you know with a message.

If you specify name, the file with that name is followed, regardless of its file descriptor.

Examples

Outputs the last 10 lines of the file myfile.txt.

Outputs the last 100 lines of the file myfile.txt.

Outputs the last 10 lines of myfile.txt, and monitors myfile.txt for updates; tail then continues to output any new lines that are added to myfile.txt.

The tail command follows the file forever. To stop it, press Ctrl + C .

tail -f access.log | grep 24.10.160.10

This is a useful example of using tail and grep to selectively monitor a log file in real time.

In this command, tail monitors the file access.log. It pipes access.log‘s final ten lines, and any new lines added, to the grep utility. grep reads the output from tail, and outputs only those lines which contain the IP address 24.10.160.10.

cat — Output the contents of a file.
head — Display the first lines of a file.
more — Display text one screen at a time.
pg — Browse page by page through text files.

Источник

Оцените статью
Adblock
detector