Меню Рубрики

Linux less go to end

Команда less в Linux

Об утилите и команде more, которая предназначена для постраничного просмотра больших текстовых файлов, мы уже писали. А сегодня расскажем о более функциональной команде less — она позволяет перематывать текст не только вперёд, но и назад, осуществлять поиск в обоих направлениях, переходить сразу в конец или в начало файла.

Особенность less заключается в том, что команда не считывает текст полностью, а загружает его небольшими фрагментами.

Синтаксис и опции less

Запись команды less в терминале выглядит так:

команда опции файл

Наиболее популярные опции:

  • -a, —search-skip-screen — не осуществлять поиск в тексте, который в данный момент отображен на экране;
  • -bn, —buffers=n — задать размер буфера памяти;
  • -c, —clear-screen — листать текст, полностью стирая содержимое экрана (построчная прокрутка работать не будет);
  • -Dxcolor, —color=xcolor — задать цвет отображаемого текста;
  • -E, —QUIT-AT-EOF — выйти, когда утилита достигнет конца файла;
  • -e, —quit-at-eof — выйти, когда утилита второй раз достигнет конца файла;
  • -F, —quit-if-one-screen — выйти, если содержимое файла помещается на одном экране;
  • -f, —force — открыть специальный файл;
  • -hn, —max-back-scroll=n — задать максимальное количество строк для прокрутки назад;
  • -yn, —max-forw-scroll=n — задать максимальное количество строк для прокрутки вперёд;
  • -i, —ignore-case — игнорировать регистр;
  • -I, —IGNORE-CASE — игнорировать регистр, даже если паттерн для поиска содержит заглавные буквы;
  • -jn, —jump-target=n — указать, в какой строке должна быть выведена искомая информация;
  • -J, —status-column — пометить строки, соответствующие результатам поиска;
  • -n, —line-numbers — не выводить номера строк;
  • N, —LINE-NUMBERS — вывести номера строк;
  • -s, —squeeze-blank-lines — заменить множество идущих подряд пустых строк одной пустой строкой;
  • -w, —hilite-unread — выделить первую строку нового фрагмента текста.

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

  • h, H — справка;
  • Space, Ctrl+V, f, Ctrl+F — прокрутить текст на один экран вперёд;
  • Enter, Return, Ctrl+N, e, Ctrl+E, j, Ctrl+J — прокрутить текст на n строк вперед, по умолчанию n=1;
  • y, Ctrl+Y, Ctrl+P, k, Ctrl+K — прокрутить текст на n строк назад, по умолчанию n=1;
  • Ctrl+ — прокрутить текст по горизонтали в конец строки;
  • Ctrl+ — прокрутить текст по горизонтали в начало строки;
  • :d — удалить текущий файл из списка файлов;
  • Ctrl+G, :f — вывести основную информацию о файле;
  • q, Q, :q, :Q, ZZ — выход.

Перечень всех опций и внутренних команд можно просмотреть в терминале, выполнив команду

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

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

Командная строка исчезнет, а в окне терминала откроется указанный вами документ. После этого его можно читать, пользуясь для прокручивания строк вперед и назад клавишами Enter и y либо другими.

Внизу окна вы увидите поле с мигающим курсором — здесь можно напечатать какую-либо внутреннюю команду, например, задать утилите паттерн поиска.

Опции нужны для того, чтобы оптимизировать отображение текста и сделать работу с утилитой более удобной. К примеру, в текстах часто встречаются множественные пустые строки. Они «съедают» место на экране, не принося никакой пользы. Поэтому к команде less стоит всегда добавлять опцию -s или —squeeze-blank-lines — она удаляет лишние пустые строки.

less -s textfile.txt

Сравните как выглядит один и тот же текст с использованием опции -s (слева) и без неё (справа).

Впрочем, утилиту less зачастую используют не для чтения текста, а для поиска определенных участков в больших документах. Если вам нужно найти то или иное слово, напечатайте в поле с мигающим курсором /текст (для поиска вниз по тексту) или ?текст (чтобы выполнить поиск less вверх по тексту) и нажмите Enter. При необходимости используйте стандартные паттерны. Все участки текста, которые соответствуют заданным условиям поиска, будут подсвечены контрастным цветом.

Если вас интересует как выйти из less, то для выхода из утилиты и возвращения к командной строке терминала нажмите q, ZZ или выполните другую команду, сигнализирующую о завершении работы.

Следует заметить, что утилита less предназначена только для просмотра документов. Она не позволяет вносить в текст правки, форматировать или пересохранять его.

Выводы

Команда less в Linux пригодится для просмотра по-настоящему больших текстовых файлов, с которыми затруднительно работать в текстовых редакторах вроде vim или с помощью утилит, загружающих весь документ сразу. Если какие-то нюансы управления утилитой less остались вам непонятны, оставьте свой вопрос в комментариях и более опытные пользователи помогут решить проблему.

Источник

Open `less` scrolled to the end

Is there a way to open less and have it scroll to the end of the file? I’m always doing less app.log and then pressing G to go to the bottom.

I’m hoping there’s something like less —end or less -exec ‘G’ .

3 Answers 3

+ will run an initial command when the file is opened

G jumps to the end

When multiple files are in play, ++ applies commands to every file being viewed. Not just the first one. For example, less ++G app1.log app2.log .

will go to the end and tail the file.

From less man page:

F Scroll forward, and keep trying to read when the end of file is reached. Normally this command would be used when already at the end of the file. It is a way to monitor the tail of a file which is growing while it is being viewed. (The behavior is similar to the «tail -f» command.)

From the less man page:

If a command line option begins with +, the remainder of that option is taken to be an initial command to less. For example, +G tells less to start at the end of the file rather than the beginning, and +/xyz tells it to start at the first occurrence of «xyz» in the file. As a special case, + acts like +g; that is, it starts the display at the specified line number (however, see the caveat under the «g» command above). If the option starts with ++, the initial command applies to every file being viewed, not just the first one. The + command described previously may also be used to set (or change) an initial command for every file.

Not the answer you’re looking for? Browse other questions tagged less or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2020.9.18.37632

Источник

Unix Less Command: 10 Tips for Effective Navigation

I personally prefer to use less command to view files (instead of opening the file to view in an editor). Less is similar to more command, but less allows both forward and backward movements. Moreover, less don’t require to load the whole file before viewing. Try opening a large log file in Vim editor and less — you’ll see the speed difference.

The navigation keys in less command are similar to Vim editor. In this article, let us look at few less command navigation and other operations which will make you a better command line warrior.

1. Less Command – Search Navigation

Once you’ve opened a log file (or any file) using less file-name, use the following keys to search. Please note that the match will be highlighted automatically by default.

Forward Search

  • / – search for a pattern which will take you to the next occurrence.
  • n – for next match in forward
  • N – for previous match in backward

Backward Search

  • ? – search for a pattern which will take you to the previous occurrence.
  • n – for next match in backward direction
  • N – for previous match in forward direction

Tip: If you dont bother about which direction the search is happening, and you want to search file path, or URL, such as “/home/ramesh/”, you can use backward search (?pattern) which will be handy as you don’t want to escape slashes each time.

2. Less Command – Screen Navigation

Use the following screen navigation commands while viewing large log files.

  • CTRL+F – forward one window
  • CTRL+B – backward one window
  • CTRL+D – forward half window
  • CTRL+U – backward half window

3. Less Command – Line navigation

In a smaller chunk of data, where you want to locate particular error, you may want to navigate line by line using these keys:

  • j – navigate forward by one line
  • k – navigate backward by one line

4. Less Command – Other Navigations

The following are other navigation operations that you can use inside the less pager.

  • G – go to the end of file
  • g – go to the start of file
  • q or ZZ – exit the less pager

5. Simulate tail -f inside less pager – Press F

Once you’ve opened a file using less command, any content that is appended to the file after that will not be displayed automatically. However, you can press F less command will show the status ‘waiting for data‘. This is as similar to ‘tail -f’.

6. Less Command – Count magic

Similar to Vim editor navigation command, you can give 10j to scroll 10 lines down, or 10k to go up by 10 lines.

  • 10j – 10 lines forward.
  • 10k – 10 lines backward.
  • CTRL+G – show the current file name along with line, byte and percentage statistics.

7. Other useful Less Command Operations

  • v – using the configured editor edit the current file.
  • h – summary of less commands
  • &pattern – display only the matching lines, not all.

8. Open any types of files using less command

As we discussed in our earlier article, you can use less command to Open & view 10 different file types.

9. Less Command – Marked navigation

When you are viewing a large log file using less command, you can mark a particular position and return back to that place again by using that mark.

  • ma – mark the current position with the letter ‘a’,
  • ‘a – go to the marked position ‘a’.

10. Less Command – Multiple file paging

Method 1: You can open multiple files by passing the file names as arguments.

Method 2: While you are viewing file1, use :e to open the file2 as shown below.

Navigation across files: When you opened more than two files ( for e.g – less * ), use the following keys to navigate between files.

  • :n – go to the next file.
  • :p – go to the previous file.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Mac os работа с mysql
  • Mac os путь к корзине
  • Mac os процесс bird
  • Mac os профиль конфигурации
  • Mac os против windows