About cat command in linux

Команда cat Linux

Команда cat — это одна из самых часто используемых команд Linux. Она часто применяется опытными пользователями во время работы с терминалом. С помощью этой команды можно очень просто посмотреть содержимое небольшого файла, склеить несколько файлов и многое другое.

Несмотря на то что утилита очень проста и решает только одну задачу в лучшем стиле Unix, она будет очень полезной. А знать о ее дополнительных возможностях вам точно не помешает. В этой статье будет рассмотрена команда cat linux, ее синтаксис, опции и возможности.

Команда cat

Название команды — это сокращения от слова catenate. По сути, задача команды cat очень проста — она читает данные из файла или стандартного ввода и выводит их на экран. Это все, чем занимается утилита. Но с помощью ее опций и операторов перенаправления вывода можно сделать очень многое. Сначала рассмотрим синтаксис утилиты:

$ cat опции файл1 файл2 .

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

  • -b — нумеровать только непустые строки;
  • -E — показывать символ $ в конце каждой строки;
  • -n — нумеровать все строки;
  • -s — удалять пустые повторяющиеся строки;
  • -T — отображать табуляции в виде ^I;
  • -h — отобразить справку;
  • -v — версия утилиты.

Это было все описание linux cat, которое вам следует знать, далее рассмотрим примеры cat linux.

Использование cat в Linux

Самое простое и очевидное действие, где используется команда cat linux — это просмотр содержимого файла, например:

Команда просто выведет все, что есть в файле. Чтобы вывести несколько файлов достаточно просто передать их в параметрах:

Как вы знаете, в большинстве команд Linux стандартный поток ввода можно обозначить с помощью символа «-«. Поэтому мы можем комбинировать вывод текста из файла, а также стандартного ввода:

Читайте также:  Multiboot usb hdd utility and windows linux crutch 2021

Теперь перейдем к примерам с использованием ранее рассмотренных опций, чтобы нумеровать только непустые строки используйте:

Также вы можете нумеровать все строки в файле:

Опция -s позволяет удалить повторяющиеся пустые строки:

А с помощью -E можно сообщить утилите, что нужно отображать символ $ в конце каждой строки:

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

Для завершения записи нажмите Ctrl+D. Таким образом можно получить очень примитивный текстовый редактор — прочитаем ввод и перенаправим его вместо вывода на экран в файл:

Возможность объединения нескольких файлов не была бы настолько полезна, если бы нельзя было записать все в один:

cat file1 file2 > file3
$ cat file3

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

Выводы

В этой статье мы рассмотрели что представляет из себя команда cat linux и как ею пользоваться. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!

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

Источник

Linux Cat Command Examples

In Linux, the “cat” is the concatenation of files which combines multiple files into a single file. There are other several uses of the cat command in Linux which we will talk in this article to give you an understanding of how it works in different scenarios.

  • How Does the Cat Command Work?
  • Display the Content of All Files
  • Display Multiple Files at Once
  • Copy the Output of One File to Another File
  • Append the Output of a File to Another File
  • Display the Line Numbers in the File
  • Create New Files
  • Sort the Output
  • Remove the Consecutive Empty Lines
  • Display the Tab Characters
  • Print the Output of a File

Let’s start the article with the cat command.

How Does the Cat Command Work?

Using the “cat” command, you can create a file, view the file content, concatenate the files, and redirect the file output. The syntax of this command as follows:

Use the previous command if you are present in the same directory. Otherwise, mention the path to that file as follows:

Different options of the cat command are listed in the following:

Читайте также:  What is rpm in red hat linux
Options Description
-n To display the line number of file content
-T To display the tab-separated characters in a line-e
-e To display the “$” at the end of lines
-s You can omit the empty lines from the output.
-a To display all the file content

To explore more options, use the following “help” utility:

Example 1: Display the Content of All Files

The common usage of the cat command is displaying the file contents. To display the file contents to a Terminal, simply type “cat” and the filename as follows:

To display all the files in a current directory, use the wildcard character with the cat command as follows:

To display only the contents of the text files in a directory, enter the following command:

Example 2: Display Multiple Files

You can also combine and display the contents of multiple files together in the Terminal using the cat command. To display multiple files simultaneously, use the following syntax:

Example 3: Copy the Output of One File to Another

It can also be utilized to copy the output of one file to another file. If not found, it first creates it. Otherwise, it overwrites the targeted file.

To copy the output of a source file to another file, use the following syntax:

An example of this is to copy the output of a testfile1 to another file named testfile_backup as follows:

This command first creates the testfile_backup file and then copies the contents of testfile1 to it.

Example 4: Append the Output of a File to Another File

Instead of overwriting the output of a targeted file in the pervious example, you can also make the cat command to append the output:

It creates the destination file if it does not already exist. Otherwise, it appends the output.

Copy Multiple Files to Another Text File/Concatenate the Files

The cat command combines several files into a single file. The following syntax can be used to concatenate file1, file2, and file3 and save them to another file named file4.txt:

For instance, we want to concatenate the output of /etc/hostname, /etc/resolv.conf, and the /etc/hosts file to another file named network.txt:

Example 5: Display the Line Numbers in File

To display the line numbers to the output of a file, simply use the -n flag as follows:

Читайте также:  Linux show big files

For instance, if you are viewing a file which contains the list of items, you can use the -n flag to display those items with a number. Remember that empty lines are also numbered as follows:

If you do not want to number the empty lines, use the -b flag as follows:

Example 6: Create a File

To create a file through the cat command, the following syntax can be used for the purpose:

After entering the previous command, enter the text that you want to store in the file. Once done, save and exit. After that, you can view the contents of your newly created file by executing the following command in the terminal:

Example 7: Sort the Output

You can also combine the sort with the cat command to sort the output alphabetically as follows:

Example 8: Remove the Consecutive Empty Lines

Sometimes, the file contains consecutive empty lines that you do not want to print. The cat command allows merging those consecutive empty lines and shows them as one empty line:

Use the following command syntax to remove the repeated empty lines:

For instance, we have the following file with consecutive empty lines:

Example 9: Display the Tab Characters

Sometimes, you have to remove the tabs from your files. Cat command can help you to find the tabs on your file using the -t flag as follows:

Example 10: Print the Output of a File

Another popular use of the cat command is in the printing contents of a document. For instance, to print the output of a file to a printing device named /dev/lp, the following syntax is used:

Conclusion

In this article, we explained through various examples on how you can use the cat command to manipulate the files in Linux. The cat command is popular among all users because of its simple syntax and the various options that it provides. Creating and viewing a file, merging, copying, and appending the file contents, printing, and a lot more can be handled with this single cat command.

About the author

Syed Minhal Abbas

I hold a master’s degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.

Источник

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