Linux head to file

Команда head linux

Команда head выводит начальные строки (по умолчанию — 10) из одного или нескольких документов. Также она может показывать данные, которые передает на вывод другая утилита.

Сегодня мы расскажем как работает эта команда для Linux и покажем, как используются на практике наиболее популярные опции head.

Команда head в Linux

Синтаксис у команды head следующий:

$ head опции файл

  • Опции — это параметр, который позволяет настраивать работу команды таким образом, чтобы результат соответствовал конкретным потребностям пользователя.
  • Файл — это имя документа (или имена документов, если их несколько). Если это значение не задано либо вместо него стоит знак «-», команда будет брать данные из стандартного вывода.

Чаще всего к команде head применяются такие опции:

  • -c (—bytes) — позволяет задавать количество текста не в строках, а в байтах. При записи в виде —bytes=[-]NUM выводит на экран все содержимое файла, кроме NUM байт, расположенных в конце документа.
  • -n (—lines) — показывает заданное количество строк вместо 10, которые выводятся по умолчанию. Если записать эту опцию в виде —lines=[-]NUM, будет показан весь текст кроме последних NUM строк.
  • -q (—quiet, —silent) — выводит только текст, не добавляя к нему название файла.
  • -v (—verbose) — перед текстом выводит название файла.
  • -z (—zero-terminated) — символы перехода на новую строку заменяет символами завершения строк.

Переменная NUM, упомянутая выше — это любое число от 0 до бесконечности, задаваемое пользователем. Оно может быть обычным либо содержать в себе множитель.

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

Самый простой способ использования команды head — с указанием имени файла, но без опций. В таком случае будут выведены на экран первые 10 строк.

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

head file-name1.txt file-name2.txt

Разумеется, файлов может быть и три, и четыре, и больше. Чтобы не возникало путаницы, их содержимое автоматически разделяется пустой строкой, а перед текстом выводится название документа.

Чтобы название файла выводилось даже в том случае, когда команде задан только один документ, следует воспользоваться опцией -v:

Если десяти строк, по умолчанию выводимых командой, окажется слишком мало или слишком много, ничто не мешает изменить их количество вручную. Для этой цели служит опция -n:

Не будем забывать об еще одном интересном свойстве этой опции. Она позволяет вывести то количество строк, которое останется после «отсечения» лишнего текста. Для этого нужно использовать не сокращенную (однобуквенную), а полную запись опции:

Читайте также:  Astra linux special edition common edition разница

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

Следует заметить, что строки «отсекаются», начиная с последней.

До этого момента мы (и команда head вместе с нами) считали количество текста построчно. Но это не обязательное условие — с таким же успехом единицей измерения может быть байт. Достаточно сообщить команде о новом правиле работы с помощью опции -с, заодно указав и количество байт, которое нужно вывести на экран (NUM):

Как и в случае с опцией —lines, можно «отсечь» ненужный объем текста, используя полную форму опции -с — —bytes. Запись команды проводится по тому же принципу и лишние байты тоже отсчитываются, начиная с конца документа:

При записи байт можно использовать буквенные суффиксы:

Кстати, команду head можно использовать не только самостоятельно, но и в сочетании с другими командами. Например, такая запись хеширует рандомно выбранную переменную среды, выводит первые 32 байта из указанного файла и отображает случайную строку из 24 символов:

echo $RANDOM | sha512sum | head -c 24 file-name.txt; echo

На этом наши примеры head linux подошли к завершению.

Выводы

Команда head linux, которая выводит начальные строки файла, — это в некотором роде антагонист команды tail (она печатает в терминале последние строки). Поскольку ее синтаксис довольно прост, у пользователей, как правило, не возникает проблем с использованием этой команды. Если у вас появились вопросы или замечания по части команды head и ее применения в Linux-системах, обязательно оставьте комментарий внизу.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Using head Command in Linux

The head command is one of the several ways to display file contents or part of it. You can also do more with it. Here are some common examples to explore.

The head command is one of the many ways to view the contents of a file in Linux terminal. But that can also be achieved by the cat command too! So why use another command? I understand. But if there was no problem with how the cat command works, the head command won’t even exist. So let’s have a look at the problem with cat. By default, the cat command prints all the text inside the file. But what if you have a file containing 1000 or more words? Your terminal will look bloated. Isn’t it? Whereas the head command can specify the number of lines to print. In this guide, I will walk you through how you can use the head command with the help of some practical examples and additional practice exercises to brush up your command-line skills. Suggested Read 📖

Читайте также:  Im miranda in linux

How to use the head command in Linux

To use any command in Linux, you will have to use the correct syntax; else, you will get an error. So let’s start with the syntax for the head command:

  • options are used to tweak the default behavior of the head command
  • file is where you give the absolute path or filename of the file

To make things easy, I will be using a simple text file named Haruki.txt with the following content:

Hear the Wind Sing (1979) Pinball, 1973 (1980) A Wild Sheep Chase (1982) Hard-Boiled Wonderland and the End of the World (1985) Norwegian Wood (1987) Dance Dance Dance (1990) South of the Border, West of the Sun (1992) The Wind-Up Bird Chronicle (1994) Sputnik Sweetheart (1999) Kafka on the Shore (2002) After Dark (2004) 1Q84 (2009-2010) Colorless Tsukuru Tazaki and His Years of Pilgrimage (2013) Men Without Women (2014) Killing Commendatore (2017)

And when you use the head command without any options, it will print the first ten lines of the file:

use head command in linux

As you can see, it skipped the last five lines!

You’ll see some command examples with text inside <>. This indicates that you need to replace the content with < and >with a suitable value.

Examples of the head command in Linux

In this section, I will walk you through some practical examples of the head command. So let’s start with the most useful one.

1. Print only the first N lines

So if you want to print first N lines, all you have to do is use the -n flag and append the number of the first N lines you want:

head -n number-of-lines Filename

So let’s say I want to print the first five lines of Haruki.txt file, then you type the following:

Print only the first N lines using the head command

2. Print everything except the last N lines

So if you want to restrict the output by not including the last N lines, all you have to do is use the same -n flag but have to use the negative number ( -n ):

So let’s say I want to exclude the last three lines and print everything else from the Haruki.txt then the command looks like this:

exlcude last N lines and print everything else using the head command in linux

3. Display the name of the file being used

As you can see, the head command won’t print the filename by default, so if you want to enable this behavior, all you have to do is use the -v flag for verbose output:

Yes, you can use more than one option at once!

So here, I printed the first five lines of the Haruki.txt file and enabled the verbose output to display the name of the file:

Display the name of the file being used

4. Use multiple files at once

So if you want to use the different files, all you have to do is append them one by one, followed by space:

Читайте также:  Какую архитектуру ядра использует linux

For example, here, I used two files and printed the first five lines of each:

head -n 5 Haruki.txt Premchand.txt

use multiple files in head command

If you notice, it automatically prints the filename, especially when dealing with multiple files.

But in cases like redirecting the essential output, you may want to remove the filename. This can easily be done using the -q flag:

remove filenames while using multiple files with the head command

5. Print characters as per the given number of bytes

So if you want to print the lines based on the byte size, you can do that using the -c flag followed by the byte size.

Remember, for almost every character, one character = 1 byte.

To do so, you can use the following syntax:

For example, here, I print characters worth 100 bytes:

Print characters as per the given number of bytes

Similarly, if you want to skip the characters from the end of the file by specifying the bytes, all you have to do is use the negative numbers:

For example, here, I skipped the last characters of the file worth 100 bytes:

skip last N characters on the basis of the byte size using the head command

Summarizing the head command

Here’s the summary of the head command with different options:

Option Description
-n Specify how many lines to print from the beginning of the file.
-n — Print everything except the last N lines.
-v Print the name of the file.
-q Remove the filename when working with multiple files.
-c Print characters as per the given number of bytes.

Get better with a simple exercise

To perform the given exercises, you can use text files, and if you don’t have any, you can use our text files from GitHub.

  1. Display the first ten lines of the file
  2. Display everything except the last five lines of a file
  3. Display the first five lines of multiple files
For intermediate users:
  1. Display the first five lines of multiple files, sorted alphabetically by file name (Hint: pipe to sort command)
  2. Display the lines from 11 to 16 (Hint: combine it with the tail command)
  3. Count the occurrence of a specific word or character in the first five lines (Hint: pipe to grep with wc command)

Just getting started with Terminal? We have a series for you!

While the terminal looks scary, you can always make the terminal look good, but what about the learning curve it takes?

For new users, we came up with a dedicated series which covers the basic commands so you can embrace the terminal:

Furthermore, you can discuss the practice questions mentioned above in our community:

I hope you now have a better understanding of the head command.

🗨 We’ll be sharing more Linux command examples every week. Stay tuned for more. And if you have questions or suggestions, the comment section is all yours.

Источник

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