Using cat on linux

Writing to Files Using cat Command on Linux

The cat command is a Unix tool used for manipulating and displaying file contents. The command gets its name from the word «concatenate» because it has, among other things, the ability to concatenate files.

In this article, we’ll go through a few easy ways to use this command to write text to a file with examples. Using cat is very straightforward, so no prior programming or Unix experience is needed to follow along.

cat Command Basics

Starting, we’ll just sum up the basics of the cat command to help you out if you’ve never used it before or need a brief overview.

Syntax

The syntax looks like this:

To quickly look up the syntax or command options, run cat with the help option:

Or, you can use the manual pages:

These commands should display the following list of options:

 -A, --show-all equivalent to -vET -b, --number-nonblank number nonempty output lines, overrides -n -e equivalent to -vE -E, --show-ends display $ at end of each line -n, --number number all output lines -s, --squeeze-blank suppress repeated empty output lines -t equivalent to -vT -T, --show-tabs display TAB characters as ^I -u (ignored) -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB --help display this help and exit --version output version information and exit 

Displaying File Contents on the Standard Output

To print the contents of a file to the standard output just name the file you want to display:

If the file is in a different directory, you’ll have to navigate to it:

We’ll be expecting to see the contents of this file, printed to the standard output, in this case — the terminal:

This is the most common use of the cat command since it makes it easy to peek into the contents of a file without opening a text editor.

Writing Text to a File Using cat

To redirect the output of the cat command from the standard output to a file, we can use the output redirection operator > :

This will overwrite the contents of filename2 with the contents of filename1 , so make sure that filename2 doesn’t contain anything you would mind losing. Now, filename2 contains:

The output redirection operator will redirect the output of any command we call. For example, let’s try it out with the pwd command, which prints the name of the current working directory:

Читайте также:  Перезапуск службы cups linux

If we take a look at the testfile now:

It contains the current working directory’s path:

If the file you are redirecting to doesn’t exist, a file by that name will be created:

$ cat filename1 > newfilename 

Concatenating Files with cat

Concatenating multiple files using cat is simple — just list the files in the desired order:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

$ cat filename1 filename2 > outputfile $ cat outputfile 

This takes the filename1 and filename2 files, concatenates them, and outputs the into a new outputfile :

Content of filename1! Content of filename2! 

Standard Input Between Files

When the name of the input file isn’t listed, cat starts reading from the standard input until it reaches EOF (end-of-file). The end-of-file signal is sent by the ctrl+d command line shortcut:

$ cat > outputfile Hello World $ cat outputfile 

We can even add text from the standard input in between files we wish to concatenate by using — to indicate where we expect standard input. If we have files such as filename1 , filename2 , and filename3 , and we want some text from the standard input in between filename1 and filename2 , we would write:

 $ cat filename1 - filename2 filename3 > output Text from standard input! $ cat output 

Checking output , we’ll see something along the lines of:

Content of filename1! Text from standard input! Content of filename2! Content of filename3! 

Appending Files with cat

In the previous examples, using the redirection operator discarded the previous contents of the output file. What if we want to append the new content to the old content? To append files we use the >> operator:

$ cat filename1 filename2 >> output $ cat output 

And that should result in:

Original output file contents. Content of filename1! Content of filename2! 

Concatenating Contents of all Files Directory with cat

To concatenate all contents of all files in a directory, we use the wildcard * :

To concatenate all contents of all files in the current working directory, we’d use:

* can also be used to concatenate all files with the same extension:

Enumerating Line Numbers

Enumeration of all lines of output is done with the -n option:

$ cat -n filename1 filename2 filename3 > output $ cat output 

Which would write something along the lines of:

 1 Content of filename1! 2 Content of filename2! 3 Content of filename3! 

Write $ at the End of Every Line

The -E option marks the end of every line in the file with the $ character:

$ cat -E filename1 filename2 filename3 > output $ cat output 

Sorting Lines of Concatenated Files by Piping

This one is a bit of a cheat. The cat command can’t sort, but we can use piping to achieve that. The pipe command ( | ) is used to turn the output of one command into the input of another. To sort the lines of a file, we’ll use both cat and another command, called sort :

$ cat filename2 filename3 filename1 | sort > output $ cat output 
Content of filename1! Content of filename2! Content of filename3! 

Conclusion

Cat is a simple, yet powerful Unix tool that comes pre-installed on most systems. It can be used on its own or in combination with other commands using pipes. Originally made by Ken Thompson and Dennis Ritchie in 1971, cat ‘s easy to use and intuitive functionalities stand the test of time.

Читайте также:  Linux piping to file

In this article, we’ve explored some of the possibilities of using the cat command to write text to files, check contents, concatenate and append files as well as enumerate lines and sort them.

Источник

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

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

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

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

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

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

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

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

cat file1 file2 > file3
$ cat file3

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

Выводы

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

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

Источник

How the cat Command works on Linux

cat , short for concatenate, is used on Linux and Unix-based systems like MacOS for reading the contents of a file, concatenating the contents with other files, and for creating new, concatenated files. It’s also frequently used to copy the contents of files.

Читайте также:  Linux mint связка ключей убрать

The syntax for cat is shown below, where x is the file name, and [OPTIONS] are optional settings which alter how cat works.

Getting the contents of a file using cat on Linux or MacOS

Using the cat command along with one file name, we can get the entire text content of a file. For example, the below command will output the content of my-file.txt into the terminal:

Similarly, we can see the contents of many files by separating them with a space. For example, the below line takes the content of my-file.txt , and my-new-file.txt , merges the content, and shows it in terminal:

cat my-file.txt my-new-file.txt 

Getting the contents of files with line numbers on Linux or MacOS

We can use the option -n to show line numbers. For example, the following command merges our two files, my-file.txt, and my-new-file.txt , and outputs the content with line numbers side by side. This is pretty useful for comparing files.

cat -n my-file.txt my-new-file.txt 

The output will look something like this:

 1 Content from my-file.txt 1 Some more content from my-new-file.txt 

Concatenating two files into a new file on Linux and MacOS

Since concatenate can output the contents of two files, we can use > again to merge two files into a totally new file. The below example takes my-file.txt and my-new-file.txt, merges their content, and puts it into a new file called my-combined-file.txt:

cat my-file.txt my-new-file.txt > my-combined-file.txt 

Putting Content from one file into another with Linux or MacOS

If all we want to do is put the contents of one file at the end of another, we can instead use >> . For example, the below command will take the content from my-file.txt, and put it at the end of my-new-file.txt, thus merging both files into my-new-file.txt:

cat my-file.txt >> my-new-file.txt 

Line Numbers

Note: if you use >> or > with the -n option, the line numbers will also be merged into your new concatenated file!

Creating an empty file on Linux or MacOS with cat

Since it’s so easy to create files with cat , we often use it to make new files. For example, the below code will create a blank file called my-file.txt, as we are concatenating a blank string into it:

How to show nonprintable characters on Linux or MacOS

Some documents or files may contain nonprintable characters. These are used to signal to applications how a file should be formatted — but they can sometimes mess up the format of files. To show nonprintable characters when using cat , we can use the -v option. This will show all nonprintable characters using caret notation, so that we can view them easily.

Nonprintable characters

All options for cat on Linux or MacOS

There are a bunch of other options which help us use cat to get the ouputs we want. We’ve already discussed -n for getting line numbers, and -v for nonprintable characters, but here are the others:

  • -b — numbers only non empty output lines, overriding -n .
  • -E — displays a $ at the end of every line.
  • -s — suppresses repeated, empty lines.
  • -T — displays tabs as ^I , so as to easily discriminate them from spaces.
  • -A — equivalent to writing -vET .

More Tips and Tricks for Linux

Источник

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