- Команда cat Linux
- Команда cat
- Использование cat в Linux
- Выводы
- Using cat Command in Linux
- Using the cat command in Linux
- 1. Create new files
- 2. Copy the file contents to a different file
- Append the content of one file to another
- 4. Show the numbers of line
- 5. Remove the blank lines
- That’s what you’ve learned so far
- 🏋️It’s time to exercise
- How the cat Command works on Linux
- Getting the contents of a file using cat on Linux or MacOS
- Getting the contents of files with line numbers on Linux or MacOS
- Concatenating two files into a new file on Linux and MacOS
- Putting Content from one file into another with Linux or MacOS
- Line Numbers
- Creating an empty file on Linux or MacOS with cat
- How to show nonprintable characters on Linux or MacOS
- Nonprintable characters
- All options for cat on Linux or MacOS
- More Tips and Tricks for 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 стандартный поток ввода можно обозначить с помощью символа «-«. Поэтому мы можем комбинировать вывод текста из файла, а также стандартного ввода:
Теперь перейдем к примерам с использованием ранее рассмотренных опций, чтобы нумеровать только непустые строки используйте:
Также вы можете нумеровать все строки в файле:
Опция -s позволяет удалить повторяющиеся пустые строки:
А с помощью -E можно сообщить утилите, что нужно отображать символ $ в конце каждой строки:
Если вы не передадите никакого файла в параметрах утилите, то она будет пытаться читать данные из стандартного ввода:
Для завершения записи нажмите Ctrl+D. Таким образом можно получить очень примитивный текстовый редактор — прочитаем ввод и перенаправим его вместо вывода на экран в файл:
Возможность объединения нескольких файлов не была бы настолько полезна, если бы нельзя было записать все в один:
cat file1 file2 > file3
$ cat file3
Вот, собственно, и все возможности команды cat, которые могут быть полезны для вас.
Выводы
В этой статье мы рассмотрели что представляет из себя команда cat linux и как ею пользоваться. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Using cat Command in Linux
The cat command is used to print the file contents of text files. At least, that’s what most Linux users use it for and there is nothing wrong with it. Cat actually stands for ‘concatenate’ and was created to merge text files. But withsingle argument, it prints the file contents. And for that reason, it is a go-to choice for users to read files in the terminal without any additional options.
Using the cat command in Linux
- [options] are used to modify the default behavior of the cat command such as using the -n option to get numbers for each line.
- Filename is where you’ll enter the filename of the file that you want to work with.
To make things easy, I will be using a text file named Haruki.txt throughout this guide which contains the following text lines:
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)
So, what will be the output when used without any options? Well, let’s have a look:
As you can see, it printed the whole text file!
But you can do a lot more than just this. Let me show you some practical examples.
1. Create new files
Most Linux users use the touch command to create new files but the same can be done using the cat command too!
The cat command has one advantage over the touch command in this case, as you can add text to the file while creating. Sounds cool. Isn’t it?
To do so, you’d have to use the cat command by appending the filename to the > as shown:
For example, here, I created a file named NewFile.txt :
Once you do that, there’ll be a blinking cursor asking you to write something and finally, you can use Ctrl + d to save the changes.
If you wish to create an empty file, then just press the Ctrl + d without making any changes.
That’s it! Now, you can use the ls command to show the contents of the current working directory:
2. Copy the file contents to a different file
Think of a scenario where you want to redirect the file content of FileA to the FileB
Sure, you can copy and paste. But what if there are hundreds or thousands of lines?
Simple. You use the cat command with the redirection of data flow. To do so, you’d have to follow the given command syntax:
If you use the above syntax to redirect file contents, it will erase the file contents of the FileB and then will redirect the file contents of the FileA.
For example, I will be using two text files FileA and FileB which contains the following:
And now, if I use the redirection from FileA to FileB, it will remove the data of FileB and then redirect the data of FileA:
Similarly, you can do the same with multiple files:
As you can see, the above command removed the data of FileC and then redirected the data of FileA and FileB.
Append the content of one file to another
There are times when you want to append data to the existing data and in that case, you’ll have to use the >> instead of single > :
For example, here, I will be redirecting two files FileA and FileB to the FileC :
cat FileA.txt FileB.txt >> FileC.txt
As you can see, it preserved the data of the FileC.txt and the data was appended at the end of it.
You can use the >> to add new lines to an existing file. Use cat >> filename and start adding the text you want and finally save the changes with Ctrl+D .
4. Show the numbers of line
You may encounter such scenarios where you want to see the number of lines, and that can be achieved using the -n option:
For example, here, I used the -n option with the Haruki.txt :
5. Remove the blank lines
Left multiple blank lines in your text document? The cat command will fix it for you!
To do so, all you have to do is use the -s flag.
But there’s one downside of using the -s flag. You’re still left with one blank space:
As you can see, it works but the results are close to the expectations.
So how would you remove all the empty lines? By piping it to the grep command:
Here, the -v flag will filter out the results as per the specified pattern and ‘^$’ is a regular expression that matches the empty lines.
And here are the results when I used it over the Haruki.txt :
Once you have the perfect output, you can redirect it to a file to save the output:
cat Haruki.txt | grep -v '^$' > File
That’s what you’ve learned so far
Here’s a quick summary of what I explained in this tutorial:
Command | Description |
---|---|
cat | Prints the file content to the terminal. |
cat >File | Create a new file. |
cat FileA > FileB | File contents of the FileB will be overridden by the FileA . |
cat FileA >> FileB | File contents of the FileA will be appended at the end of the FileB . |
cat -n File | Shows the number of lines while omitting the file contents of the File. |
cat File | more | Piping the cat command to the more command to deal with large files. Remember, it won’t let you scroll up! |
cat File | less | Piping the cat command to the less command, which is similar to above, but it allows you to scroll both ways. |
cat File | grep -v ‘^$’ | Removes all the empty lines from the file. |
🏋️It’s time to exercise
If you learned something new, executing it with different possibilities is the best way to remember.
And for that purpose, here are some simple exercises you can do with the cat command. They will be super basic as cat too is one of the most basic commands.
- How would you create an empty file using the cat command?
- Redirect output produced by the cat command to a new file IF.txt
- Can you redirect three or more file inputs to one file? If yes, then how?
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.
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 .