Что такое cat в linux
Перейти к содержимому

Что такое cat в linux

  • автор:

Linux Cat Command: Usage and Examples

The cat command is one of the most useful Linux commands you can learn. It derives its name from the word concatenate and let you create, merge or print files in the standard output screen or to another file and much more.

It does not require you to install anything since it comes pre-installed with the coreutils package in any Debian or Red Hat based system.

In this tutorial, we will cover the common usages of the Linux cat command explaining its features.

Cat Command Syntax

Before we start exploring the article’s subject, we should log into the VPS using SSH, and quickly check the basic syntax. The command takes a filename as an argument along with options to specify particular operations.

To find all the available options, just type cat –help from the terminal.

Creating a File with the Cat Command

Using the cat command you can quickly create a file and put text into it. To do that, use the > redirect operator to redirect the text in the file.

The file is created, and you can begin populating it with text. To add multiple lines of text just press Enter at the end of each line. Once you’re done, hit CTRL+D to exit the file.

To verify that the file is indeed created by the command used above, just use the following ls command in the terminal:

Viewing the Content of a File with the Cat Command

This is one of the most basic usages of the cat command. Without any options, the command will read the contents of a file and display them in the console.

To prevent scrolling large files, you might want to add the option | more to output through the less or more display:

You can also display the content of more than one file. For example, to display content of all text files, use the following command in the terminal:

Redirecting Content Using the Cat Command

Rather than displaying the contents of a file in the console you can redirect the output to another file using the option >. The command line would look like this:

If the destination file does not exist then the command will create it, or overwrite an existing one by the same name.

To append the contents of the destination file, use the >> option along with the cat command:

Concatenating Files with the Cat Command

This command also lets you concatenate multiple files into a single one. Basically it functions exactly like the redirection feature above, but with multiple source files.

Like earlier, the above command will create the destination file if it does not exist, or overwrite an existing one with the same name.

Highlighting Line Ends with the Cat Command

The cat command can also mark line ends by displaying the $ character at the end of each line. To use this feature, use the -E option along with cat command:

Display Line Numbers with the Cat Command

With the cat command you can also display the contents of a file along with line numbers at the beginning of each one. To use this feature, use the -n option with cat command:

Displaying Non-Printable Characters with the Cat Command

To display all non-printable characters use the -v option along with cat command like in the following example:

To display tab characters only, use -T:

The tab characters will be shown as ^I

Suppressing Empty Lines with the Cat Command

To suppress repeated empty lines, and safe space on your display you can use the -s option. Keep in mind that this option will keep one blank line by removing the repeated empty lines only. The command would look like this:

Numbering Non-Empty Lines with the Cat Command

To display non-empty lines with line numbers printed before them use the -b option. Remember the -b option will override the -n option:

Displaying a File in Reverse Order With the Cat Command

To view the contents of a file in reverse order, starting with the last line and ending with the first, just use the tac command, which is just cat in reverse:

Conclusion

That’s it. You now know all the basic features and functions of the cat command. You will now have the basic understanding to put it to good use. For more information on the cat command, you can always invoke manual page of cat with the command man cat !.

We hope this article helped you better your Linux Terminal skills. See you in the next one!

Learn More Linux Commands for Reading Files

Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.

The Cat Command in Linux — Concatenation Explained with Bash Examples

Quantum Backdoor

Cat in Linux stands for concatenation (to merge things together) and is one of the most useful and versatile Linux commands. While not exactly as cute and cuddly as a real cat, the Linux cat command can be used to support a number of operations utilizing strings, files, and output.

The cat command has three primary purposes involving text files:

  • Create
  • Read/Display
  • Update/Modify

We’ll go over each of these in turn to show the commands and options associated with each operation.

Getting Started

To start out, let’s create a couple of files called foo.txt and spam.txt.

Let’s start by creating foo.txt with the command cat > foo.txt from the Linux command line.

Warning: If there is already a file named foo.txt, the cat command using the > operator WILL overwrite it.

From here the prompt will display a newline that will allow us to input the text we want. For this example we’ll use:

To get back to the command line and create the text file we use CTRL + D.

Now let’s create spam.txt with cat > spam.txt and put in the following:

If we wanted to append or add more text to these files we would use cat >> FILENAME and input the text we want to use.

Note that the >> operator is used for appending as opposed to the > operator.

Instead of having to open a text editor, we were able to create a quick and simple text file from the command line, saving us time and effort.

The key takeaway from this section is that we use cat > FILENAME to create or overwrite a file. Additionally, we can use cat >> FILENAME to append to a file that's already there. Then after typing in the text we want we use CTRL + D to exit the editor, return to the command line, and create the file.

Reading Rainbow

Now that we’ve created something let’s take a look at what we’ve made.

Notice how we don’t have a > or a >> operator in the following command, only cat and the filename.

The command cat foo.txt will display the following:

So cat foo.txt will let us read the file, but let's see what else we can do.

Say we wanted to figure out how many lines a file we were working on was. For this the -n option comes in handy.

With the command cat -n foo.txt we can see how long our file is:

With -n we can get an idea of how many lines the file we’re working with has. This can come in handy when we’re iterating over a file of a fixed length.

ConCATenating files

Ok, so we’ve seen that cat can create and display files, but what about concatenating (combining) them?

For this example we’ll use files foo.txt and spam.txt. If we want to get fancy we can take a look at the contents of both files at the same time. We’ll use the cat command again, this time using cat foo.txt spam.txt .

cat foo.txt spam.txt results in the following:

Note that the above only DISPLAYS the two files. At this point we haven’t concatenated them into a new file yet.

To concatenate the files into a new file we want to use cat foo.txt spam.txt > fooSpam.txt which gives us the result into a new file fooSpam.txt.

Using cat fooSpam.txt outputs the following to the terminal:

This command is also useful for when we want to concatenate more than two files into a new file.

The takeaways here are we can view multiple files with cat FILENAME1 FILENAME 2 .

Furthermore we can concatenate multiple files into one file with the command cat FILENAME1 FILENAME 2 > FILENAME3 .

Other Fun Things to do With Cat(s)

Let’s say we’re working with a file and we keep getting errors for some reason before the end of the file — and it looks like it might have more lines than we expected it to.

To investigate the file a bit further and possibly solve our problem we can use the -A switch. The -A option will show us where lines end with a $, it will show us tab characters with a ^I, and it also displays other non-printing characters.

If we were looking at an example of a non-printable text file with cat nonPrintExample.txt we might get out something like this:

Which is OK but may not tell us a full story of a character or string that might be causing us issues.

Whereas cat -A nonPrintExample.txt might give us more useful output:

Here, we get a clearer representation of what might be going on between tabs, line feeds, returns, and other characters.

The takeaway here is that cat -A FILENAME can tell us more in-depth details about the file that we’re working with.

This article should give you a good overview of the cat command, what it can do, and its functionality.

cat and tac

cat derives its name from concatenation and provides other nifty options too.

tac helps you to reverse the input line wise, usually used for further text processing.

Creating text files

Yeah, cat can be used to write contents to a file by typing them from the terminal itself. If you invoke cat without providing file arguments or stdin from a pipe, it will wait for you to type the content. After you are done typing all the text you want to save, press Enter key and then Ctrl+d key combination. If you don’t want the last line to have a newline character, press Ctrl+d twice instead of Enter and Ctrl+d . See also unix.stackexchange: difference between Ctrl+c and Ctrl+d.

In the above example, the output of cat is redirected to a file named greeting.txt . If you don’t redirect the stdout , each line will be echoed as you type. You can check the contents of the file you just created by using cat again.

Here Documents is another popular way to create such files. Especially in shell scripts, since pressing Ctrl+d interactively won’t be possible. Here’s an example:

The termination string is enclosed in single quotes to prevent parameter expansion, command substitution, etc. You can also use \string for this purpose. If you use instead of , you can use leading tab characters for indentation purposes. See bash manual: Here Documents and stackoverflow: here-documents for more details.

Note that creating files as shown above isn’t restricted to cat , it can be applied to any command waiting for stdin .

Concatenate files

Here’s some examples to showcase cat ‘s main utility. One or more files can be given as arguments.

Visit the cli_text_processing_coreutils repo to get all the example files used in this book.

To save the output of concatenation, use your shell’s redirection features.

Accepting stdin data

You can represent stdin data using — as a file argument. If file arguments are not present, cat will read from stdin data if present or wait for interactive input as seen earlier.

Squeeze consecutive empty lines

As mentioned before, cat provides many features beyond concatenation. Consider this sample stdin data:

You can use the -s option to squeeze consecutive empty lines to a single empty line. If present, leading and trailing empty lines will also be squeezed, won’t be completely removed. You can modify the below example to test it out.

Prefix line numbers

The -n option will prefix line number and a tab character to each input line. The line numbers are right justified to occupy a minimum of 6 characters, with space as the filler.

Use -b option instead of -n option if you don’t want empty lines to be numbered.

Use nl command if you want more customization options for numbering.

Viewing special characters

Characters like backspace and carriage return will mangle the contents if viewed naively on the terminal. Characters like NUL won’t even be visible. You can use the -v option to show such characters using the caret notation (see wikipedia: Control code chart for details). See this unix.stackexchange thread for non-ASCII character examples.

The -v option doesn’t cover the newline and tab characters. You can use the -T option to spot tab characters.

The -E option adds a $ marker at the end of input lines. This is useful to spot invisible trailing characters.

  • -e option is equivalent to -vE
  • -t option is equivalent to -vT
  • -A option is equivalent to -vET

Useless use of cat

Using cat to view the contents of a file, to concatenate them, etc is well and good. But, using cat when it is not needed is a bad habit that you should avoid. See wikipedia: UUOC and Useless Use of Cat Award for more details.

Most commands that you’ll see in this book can directly work with file arguments, so you shouldn’t use cat and pipe the contents for such cases. Here’s a single file example:

If you prefer having the file argument before the command, you can still use your shell’s redirection feature to supply input data instead of cat . This also applies to commands like tr that do not accept file arguments.

Such useless use of cat might not have a noticeable negative impact unless you are dealing with large input files. Especially for commands like tac and tail which will have to wait for all the data to be read instead of directly processing from the end of the file if they had been passed as arguments (or using shell redirection).

If you are dealing with multiple files, then the use of cat will depend upon the results desired. Here’s some examples:

For some use cases like in-place editing with sed , you can’t use cat or shell redirection at all. The files have to be passed as arguments only. To conclude, don’t use cat just to pass the input as stdin for another command unless you really need to.

tac will display the input lines in reversed order. If you pass multiple input files, each file content will be reversed separately. Here’s some examples:

If the last line of input doesn’t end with a newline, the output will also not have that newline character.

Reversing input lines makes some of the text processing tasks easier. For example, if there multiple matches but you want only the last such match. See my ebooks on GNU sed and GNU awk for more such use cases.

The log.txt input file has multiple lines containing warning . The task is to fetch lines based on the last match. Tools like grep and sed have features to easily match the first occurrence, so applying tac on the input helps to reverse the condition from last match to first match. Another benefit is that the first tac will stop reading input contents after the match is found in the above examples.

Use the rev command if you want each input line to be reversed character wise.

Customize line separator for tac

By default, the newline character is used to split the input content into lines. You can use the -s option to specify a different string to be used as the separator.

When the custom separator occurs before the content of interest, use the -b option to print those separators before the content in the output as well.

The separator will be treated as a regular expression if you use the -r option as well.

See Regular Expressions chapter from my GNU grep ebook if you want to learn about regexp syntax and features.

Команда 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 стандартный поток ввода можно обозначить с помощью символа «-«. Поэтому мы можем комбинировать вывод текста из файла, а также стандартного ввода:

cat file — file1

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

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

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

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

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

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

cat > file2
$ cat file2

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

cat file1 file2 > file3
$ cat file3

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

Выводы

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

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

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

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