- Команда more в Linux
- Синтаксис и опции more
- Примеры использования more
- Выводы
- How to list the first or last 10 lines from a file without decompressing it in linux [closed]
- 2 Answers 2
- How do you keep only the last n lines of a log file?
- 8 Answers 8
- Install
- Documentation
- Display the last lines of a file in Unix
- Remove the last line from a file in Bash
- 15 Answers 15
- For large files
Команда more в Linux
Утилита more предназначена для постраничного просмотра файлов в терминале Linux. Своим названием она обязана надписи more (в русскоязычном варианте — дальше), появляющейся внизу каждой страницы.
Команда more linux — одна из самых примитивных команд для работы с текстом. Её ближайшая родственница — команда less — обладает куда большим набором опций и дополнительных возможностей. Давайте разберемся с её синтаксисом и примерами использования.
Синтаксис и опции more
В эмуляторе терминала Linux команда записывается так:
$ more опции файл
Список опций команды:
- -d — вывод информации в конце страницы о клавишах, использующихся для продолжения работы, завершения её или получения инструкций;
- -l — игнорирование в тексте символа разрыва страницы;
- -f — подсчёт числа логических строк вместо экранных;
- -p — очистка экрана терминала для того, чтобы пользователю не пришлось пользоваться прокруткой перед выводом следующей порции текста;
- -c — устранение потребности в прокрутке (как и -p) — отображение текста, начиная с верха экрана, и стирание при этом предыдущего вывода построчно;
- -s — замена нескольких пустых строк, расположенных подряд, одной пустой строкой;
- -u — удаление подчёркивания;
- -n — отображение n-го количества строк;
- +n — отображение текста, начиная со строки с номером n;
- +/строка — поиск в файле указанной строки и начало вывода текста именно с неё;
- —help — вызов справки;
- -v (—version) — вывод на экран текущей версии утилиты.
Также у команды more есть собственные горячие клавиши и интерактивные команды:
- h (?) — помощь (вывод информации только об интерактивных командах);
- ПРОБЕЛ — отображение следующей порции текста (по умолчанию количество строк зависит от текущего размера окна терминала);
- z — то же, что и ПРОБЕЛ;
- ENTER — вывод текста построчно (шаг команды — одна строка);
- d (^D) — прокрутка текста на количество строк, соответствующее размеру терминала;
- q (Q) — выход из утилиты;
- s — переход на одну строку вперёд;
- f — переход на одну экранную страницу вперёд;
- b (^B) — переход на одну экранную страницу назад;
- ‘ — возвращение к месту начала поиска;
- = — отображение текущего количества строк;
- /pattern — поиск с использованием регулярных выражений;
- n — поиск слов и фраз, соответствующих последнему использованному регулярному выражению;
- !command (:command) — выполнение команды в субоболочке;
- v — открытие файла в текстовом редакторе, назначенном по умолчанию, а если таковой не найден, использование консольного текстового редактора для открытия файла;
- ^L — удаление с экрана всего, кроме содержимого файла;
- :n — переход к следующему файлу;
- :p — переход к предыдущему файлу;
- :f — вывод названия текущего файла и количества строк в нём;
- . — повторное выполнение предыдущей команды.
Примеры использования more
Для того, чтобы просмотреть текст из файла, применяется команда:
Также в команде можно перечислить несколько имён файлов одно за другим, разделяя их пробелом. Содержимое этих файлов будет выведено в том же порядке. Пример:
more abc1.txt dfg2.txt
Если файл находится не в текущей директории, нужно указывать его полный адрес.
Порой необходимо вывести на экран не весь текст, а только его часть. Для таких случаев предусмотрены опции — (минус) и + (плюс), рядом с которыми указывается число строк. К примеру, чтобы увидеть содержимое файла, начиная с 8-й строки, следует добавить к команде опцию +8, а чтобы команда выводила результат, состоящий максимум из 5-ти строк, опцию -5:
more +8 -5 example-file-for-more-command.txt
По умолчанию команда more Linux считает строкой именно экранную строку — количество символов, которое помещается в один ряд по ширине окна. Для выполнения счёта в логических строках (при наборе текста они разделяются нажатием Enter), используется опция -f. Пример:
more -f +8 -5 example-file-for-more-command.txt
Впрочем, more умеет работать не только с текстовыми файлами — в неё можно перенаправлять вывод других команд (конвейеризация). Первой указывается основная команда, второй — more с требуемыми опциями. Команды обязательно разделяются вертикальной чертой. Пример:
locate bin | more -10
Когда команда вывела часть текста и бездействует в ожидании дальнейших действий пользователя можно выполнять интерактивные команды. Они нужны для управления выводом.
Например, для того, чтобы узнать номер текущей строки, следует нажать клавишу =, а чтобы просмотреть файл в текстовом редакторе — клавишу v.
Следует заметить, что не все интерактивные команды могут быть выполнены, если в утилиту перенаправлен вывод другой команды. Открытие текстового редактора, как и переход на одну страницу назад (b или ^B) работает только при просмотре текстовых файлов.
Для того, чтобы получить список всех интерактивных команд, следует нажать клавишу h.
Выводы
Эта вполне подходит для выполнения наиболее тривиальных задач при просмотра текста. У неё простой синтаксис, мало опций и небольшое количество дополнительных возможностей для управления выводом, однако, иногда и этого набора более чем достаточно.
Источник
How to list the first or last 10 lines from a file without decompressing it in linux [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 8 years ago .
I have a .bz2 file. I want to list the first or last 10 lines without decompress it as it is too big. I tried the head -10 or tail -10 but I see gibberish. I also need to compare two compressed file to check if they are similar or not. how to achieve this without decompressing the files ?
EDIT: Similar means identical (have the same content).
2 Answers 2
While bzip2 is a block-based compression algorithm, so in theory you could just find the particular blocks you want to decompress, this would be complicated (e.g. what if the last ten lines you ultimately want to see actually spans two or more compressed blocks?).
To answer your immediate question, you can do this, which does actually decompress the entire file, so is in a sense wasteful, but it doesn’t try to store that file anywhere, so you don’t run into storage capacity issues:
If your distribution doesn’t include bzcat (which would be a bit unusual in my experience), bzcat is equivalent to bzip2 -d -c .
However, if your ultimate goal is to compare two compressed files (that may have been compressed at different levels, and so comparing the actual compressed files directly doesn’t work), you can do this (assuming bash as your shell):
This will decompress both files and compare the uncompressed data byte-by-byte without ever storing either of the decompressed files anywhere.
Источник
How do you keep only the last n lines of a log file?
A script I wrote does something and, at the end, appends some lines to its own logfile. I’d like to keep only the last n lines (say, 1000 lines) of the logfile. This can be done at the end of the script in this way:
but is there a more clean and elegant solution? Perhaps accomplished via a single command?
8 Answers 8
It is possible like this, but as others have said, the safest option is the generation of a new file and then a move of that file to overwrite the original.
The below method loads the lines into BASH, so depending on the number of lines from tail , that’s going to affect the memory usage of the local shell to store the content of the log lines.
The below also removes empty lines should they exist at the end of the log file (due to the behaviour of BASH evaluating «$(tail -1000 test.log)» ) so does not give a truly 100% accurate truncation in all scenarios, but depending on your situation, may be sufficient.
The utility sponge is designed just for this case. If you have it installed, then your two lines can be written:
Normally, reading from a file at the same time that you are writing to it is unreliable. sponge solves this by not writing to myscript.log until after tail has finished reading it and terminated the pipe.
Install
To install sponge on a Debian-like system:
To install sponge on a RHEL/CentOS system, add the EPEL repo and then do:
Documentation
From man sponge :
sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before writing the output file. This allows constructing pipelines that read from and write to the same file.
definitely «tail + mv» is much better! But for gnu sed we can try
For the record, with ed you could do something like
This opens infile and r eads in the output of tail -n 1000 infile (i.e. it inserts that output before the 1st line) and then delete from what was initially the 1st line to the end of file. Replace ,p with w to edit the file in-place.
Keep in mind though that ed solutions aren’t suitable for large files.
What you can do in your script is implement the logic of log rotation. Do all the logging through a function:
This function, firstly, does something like:
then, it checks the size of the file or somehow decides that the file requires rotation. At that point, the file logfile.1 , if it exists, is removed, the file logfile.0 , if it exists, is renamed to logfile.1 and logfile is renamed to logfile.0 .
Deciding whether to rotate could be based on a counter maintained in the script itself. When it hits 1000, it is reset to zero.
If always strictly trimming to 1000 lines is a requirement, the script could count the number of lines in the log file when it starts, and initialize the counter accordingly (or if the count already meets or exceeds 1000, do the rotation immediately).
Or you could obtain the size, such as with wc -c logfile and do the rotation based on exceeding a certain size. This way the file never has to be scanned to determine the condition.
I did use, instead of mv , the cp command to achieve it that you are able to have some logfiles right in place where a Software is running. Maybe in the different User home dir or in the app dir and do have all logs in one place as hardlinks. If you use the mv command you lose the hard link. If you use the cp command instead you will keep this hard link.
my code is something like:
So if the files are on the same Filesystem you may give as well some different rights to the users and in the $
If it is the mv command you lose the hardlink between the files and so your second file is not more connected to the first one — maybe placed some where else.
If on the other place you don’t allow someone to erase the file your logs stay together and be nice controlled via your own script.
logrotate maybe nicer. But I am happy with this solution.
Don’t be disturbed by the «» but in my case there are some files with spaces and other special letters in and If I don’t do the «» around or the <> the whole lot doesn’t work nice.
Источник
Display the last lines of a file in Unix
Use the Unix command tail to read from standard input or a file and send the result to standard output (that is, your terminal screen). The format for using the tail command is:
Everything in brackets is an optional argument. If you don’t specify a filename, tail uses standard input.
Tail begins at distance +number from the beginning or -number from the end of the input. The number is counted in units of lines, blocks, or characters, according to the appended options -l , -b , or -c . When you don’t specify a unit, tail operates based on lines.
Specifying -r causes tail to print lines from the end of the file in reverse order. The default for -r is to print the entire file this way. Specifying -f causes tail not to quit at the end of the file, but rather to reread the file repeatedly (useful for watching a «growing» file such as a log file).
For example, given a file containing the English alphabet with each letter on a separate line, the command:
You can use tail with pipes. For example, to see the sizes of the last few files in the current directory, you could enter at the Unix prompt:
To save this information in a file in the current directory named mylist , at the Unix prompt, enter:
For more detailed information on tail , consult the Unix manual page by entering at the prompt:
At Indiana University, for personal or departmental Linux or Unix systems support, see Get help for Linux or Unix at IU.
Источник
Remove the last line from a file in Bash
I have a file, foo.txt , containing the following lines:
I want a simple command that results in the contents of foo.txt being:
15 Answers 15
The -i option does not exist in GNU sed versions older than 3.95, so you have to use it as a filter with a temporary file:
Of course, in that case you could also use head -n -1 instead of sed .
MacOS:
On Mac OS X (as of 10.7.4), the equivalent of the sed -i command above is
This is by far the fastest and simplest solution, especially on big files:
if You want to delete the top line use this:
which means output lines starting at line 2.
Do not use sed for deleting lines from the top or bottom of a file — it’s very very slow if the file is large.
For large files
I had trouble with all the answers here because I was working with a HUGE file (
300Gb) and none of the solutions scaled. Here’s my solution:
Or alternatively, as a one liner:
In words: Find out the length of the file you want to end up with (length of file minus length of length of its last line, using bc ), and set that position to be the end of the file (by dd ing one byte of /dev/null onto it).
This is fast because tail starts reading from the end, and dd will overwrite the file in place rather than copy (and parse) every line of the file, which is what the other solutions do.
NOTE: This removes the line from the file in place! Make a backup or test on a dummy file before trying it out on your own file!
Источник