- 📑 Команда cat и примеры её использования в Linux
- Общий синтаксис команды Cat
- 1. Отобразить содержимое файла
- 2. Просмотр содержимого нескольких файлов в терминале
- 3. Создание файла с помощью команды Cat
- 4. Использование команды Cat с опциями more и less
- 5. Отображение номеров строк в файле с помощью cat
- 6. Отображение $ в конце строки и вместо пробелов между абзацами
- 7. Отображение нескольких файлов одновременно
- 8. Перенаправление стандартного вывода оператора cat.
- 9. Добавление содержимого файла в существующий файл
- 10. Перенаправление нескольких файлов в один файл
- 11. Сортировка содержимого нескольких файлов в одном файле
- cat command in Linux / Unix with Examples
- Purpose
- cat command syntax
- cat command in Linux with examples
- Display A File With cat Command
- Create A File With cat Command
- Viewing A Large File With cat Command And Shell Pipes
- How To Combine Two Or More Files Using cat Command
- How To Append Data To A Text File
- Task: Number All Output Lines
- How To View Non-printing Characters
- Viewing All Files
- Print Files
- Joining Binary Files
- Fooling Programs
- Testing Audio Device
- Команда cat Linux
- Команда cat
- Использование cat в Linux
- Выводы
- Linux cat command
- Description
- Displaying text files
- Copy a text file
- Append a text file’s contents to another text file
- Incorporating standard input into cat output
- Syntax
- Options
- Examples
- Related commands
📑 Команда cat и примеры её использования в Linux
Команда cat (сокращение от «concatenate» или «объединить») является одной из наиболее часто используемых команд в операционных системах Linux/Unix. команда cat позволяет нам создавать один или несколько файлов, просматривать содержимое файла, объединять файлы и перенаправлять вывод в терминале или файлах.
Общий синтаксис команды Cat
1. Отобразить содержимое файла
В приведенном ниже примере будет выведено на терминал содержимое файла /etc/passwd.
2. Просмотр содержимого нескольких файлов в терминале
В приведенном ниже примере он отобразит содержимое файла test и test1 в терминале.
3. Создание файла с помощью команды Cat
Создание пустого файла под названием файл test2 с помощью приведенной ниже команды.
После этого система ожидает ввода от пользователя. Введите нужный текст и нажмите CTRL+D, чтобы выйти. Текст будет записан в файл test2. Вы можете просмотреть содержимое файла с помощью следующей команды cat.
4. Использование команды Cat с опциями more и less
Если файл с большим количеством содержимого не помещается на один экран и прокручивается очень быстро, мы можем использовать параметры more и less с помощью команды cat, как показано ниже.
5. Отображение номеров строк в файле с помощью cat
С помощью опции -n вы можете видеть номера строк файла song.txt на терминале.
6. Отображение $ в конце строки и вместо пробелов между абзацами
С помощью опции -e можно вывести «$» в конце каждой строки, а также если есть какой-либо пробел между абзацами. Эта опция полезна для сжатия нескольких строк в одну строку.
7. Отображение нескольких файлов одновременно
В приведенном ниже примере у нас есть три файла test, test1 и test2, и мы можем просматривать содержимое этих файлов в порядке следования имен файлов.
В качестве разделителя имен файлов нужно использовать «;» (точка с запятой).
8. Перенаправление стандартного вывода оператора cat.
Мы можем перенаправить стандартный вывод файла в новый файл или существующий файл с символом «>» (больше). Осторожно, существующее содержимое test1 будет перезаписано содержимым файла test.
9. Добавление содержимого файла в существующий файл
Добавляется в существующий файл с помощью символа «>>» (двойное больше). Здесь содержимое тестового файла будет добавлено в конец файла test1.
10. Перенаправление нескольких файлов в один файл
Это создаст файл с именем test3, и весь вывод будет перенаправлен во вновь созданный файл.
11. Сортировка содержимого нескольких файлов в одном файле
Это создаст файл test4, и вывод команды cat будет передан для сортировки, а результат будет перенаправлен во вновь созданный файл.
Источник
cat command in Linux / Unix with Examples
I am a new Linux and Unix system user. How do I use cat command on Linux or Unix-like operating systems? Can you provide basic examples and syntax usage for cat command?
The cat (short for concatenate) command is one of the most frequently used flexible commands on Linux, Apple Mac OS X, Unix, *BSD (FreeBSD / OpenBSD / NetBSD) operating systems.
cat command details | |
---|---|
Description | Concatenation files |
Category | File Management |
Difficulty | Easy |
Root privileges | No |
Est. reading time | 6 mintues |
Table of contents
|
The cat command is used for:
- Display text file on screen
- Read text file
- Create a new text file
- File concatenation
- Modifying file
- Combining text files
- Combining binary files
Purpose
Basic file operation on a text file such as displaying or creating new files.
cat command syntax
The basic syntax is as follows:
cat [options] filename
cat file1
cat > file2
cat file3 | command
cat file4 | grep something
cat command in Linux with examples
Display A File With cat Command
To view a file, enter:
Create A File With cat Command
To create a file called “foo.txt”, enter:
cat >foo.txt
Type the following text:
You need to press [CTRL] + [D] i.e. hold the control key down, then tap d. The > symbol tells the Unix / Linux system that what is typed is to be stored into the file called foo.txt (see stdout for more information). To view a file you use cat command as follows:
cat foo.txt
Viewing A Large File With cat Command And Shell Pipes
If the file is too large to fit on the computer scree, the text will scroll down at high speed. You will be not able to read. To solve this problem pass the cat command output to the more or less command as follows:
The more and less command acts as shell filters. However, you can skip the cat command and directly use the Linux / Unix more & less command like this:
How To Combine Two Or More Files Using cat Command
You can combine two files and creates a new file called report.txt, enter:
How To Append Data To A Text File
To append (add data to existing) data to a file called foo.txt, enter:
Task: Number All Output Lines
Type the following command:
Fig.01: Number all output lines with cat command
How To View Non-printing Characters
To display TAB characters as ^I, enter:
cat -T filename
To display $ at end of each line, enter:
Use ^ and M- notation, except for LFD and TAB and show all nonprinting:
To show all, enter:
cat -A fileName
OR
cat -vET fileName
Sample outputs:
Fig.02: Unix / Linux cat command: View Non-printing Characters
Viewing All Files
You can simply use the shell wildcard as follows:
cat *
To view only (c files) *.c files, enter:
cat *.c
Another option is bash for loop, or ksh for loop:
Print Files
You can directly send a file to to the printing device such as /dev/lp
cat resume.txt > /dev/lp
On modern systems /dev/lp may not exists and you need to print a file using tool such as lpr:
cat resume.txt | lpr
OR
lpr resume.txt
Joining Binary Files
You can concatenate binary files. In good old days, most FTP / HTTP downloads were limited to 2GB. Sometime to save bandwidth files size were limited to 100MB. Let us use wget command to grab some files (say large.tar.gz was split to 3 file on remote url):
wget url/file1.bin
wget url/file2.bin
wget url/file3.bin
Now combine such files (downloaded *.bin) with the cat command easily:
Another example with the rar command under Unix and Linux:
Fooling Programs
You can use the cat command to fool many programs. In this example bc thinks that it is not running on terminals and it will not displays its copyright message. The default output:
bc -l
Samples session:
Now try with the cat command:
bc -l | cat
Samples session:
Testing Audio Device
You can send files to sound devices such as /dev/dsp or /dev/audio to make sure sound output and input is working:
You can simply use the following command for recording voice sample and play back with it cat command:
Источник
Команда 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 и как ею пользоваться. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
Linux cat command
On Unix-like operating systems, the cat command reads data from files, and outputs their contents. It is the simplest way to display the contents of a file at the command line.
This page covers the GNU/Linux version of cat.
Description
cat stands for «catenate.» It is one of the most commonly-used commands in Unix-like operating systems. It can be used to:
- Display text files
- Copy text files into a new document
- Append the contents of a text file to the end of another text file, combining them
Displaying text files
The simplest way to use cat is to give it the name of a text file. It displays the contents of the text file on the screen. For instance:
. will read the contents of mytext.txt and send them to standard output (your terminal screen). If mytext.txt is very long, they will zoom past and you only see the last screen’s worth of your document.
If you want to view the document page-by-page or scroll back and forth through the document, you can use a pager or viewer such as pg, more, or less.
If you specify more than one file name, cat displays those files one after the other, catenating their contents to standard output. So this command:
Will print the contents of those two text files as if they were a single file.
Copy a text file
Normally you would copy a file with the cp command. You can use cat to make copies of text files in much the same way.
cat sends its output to stdout (standard output), which is usually the terminal screen. However, you can redirect this output to a file using the shell redirection symbol «>«.
For instance, this command:
. will read the contents of mytext.txt and send them to standard output; instead of displaying the text, however, the shell will redirect the output to the file newfile.txt. If newfile.txt does not exist, it is created. If newfile.txt already exists, it will be overwritten and its previous contents are lost, so be careful.
Similarly, you can catenate several files into your destination file. For instance:
. will read the contents of mytext.txt and mytext2.txt and write the combined text to the file newfile.txt. Again, if newfile.txt does not already exist, it is created; if it already exists, it is overwritten.
Append a text file’s contents to another text file
Instead of overwriting another file, you can also append a source text file to another using the redirection operator «>>«.
. will read the contents of mytext.txt, and write them at the end of another-text-file.txt. If another-text-file.txt does not already exist, it is created and the contents of mytext.txt will be written to the new file.
The cat command also works for multiple text files as well:
. will write the combined contents of mytext.txt and mytext2.txt to the end of another-text-file.txt.
Incorporating standard input into cat output
cat reads from standard input if you specify a hyphen («—«) as a file name. For example, if you have a file, list.txt, which contains the following text:
. you could use the echo command to output text, pipe that output to cat, and instruct cat to catenate it with the file’s contents, like this:
. which would output the following text:
In short, cat is a simple but very useful tool for working with the data in text files, system logs, configuration files, and any other human-readable data stored in a file.
Syntax
Options
These options are available on GNU cat, which is standard on most Linux distributions. If you are using a different Unix-like operating system (BSD, for example), some of these options may not be available; check your specific documentation for details.
-A, —show-all | Equivalent to -vET. |
-b, —number-nonblank | Number non-empty output lines. This option 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. |
-v, —show-nonprinting | Use ^ and M- notation, except for LFD and TAB. |
—help | Display a help message, and exit. |
—version | Output version information, and exit. |
Examples
Read the contents of file.txt and display them on the screen.
Reads the contents of file1.txt and file2.txt, and displays them in order on the terminal screen.
Read the contents of file.txt and write them to newfile.txt, overwriting anything newfile.txt previously contained. If newfile.txt does not exist, it is created.
Read the contents of file.txt and append them to the end of another-file.txt. If another-file.txt does not exist, it is created.
Display the contents of file.txt, omitting any repeated blank lines.
Related commands
cp — Copy files and directories.
ed — A simple text editor.
less — Scrolling text viewer.
more — Display text one screen at a time.
pico — A simple text editor.
pg — Browse page by page through text files.
tac — Output the contents of files in reverse order.
tee — Route a file’s contents to multiple outputs.
touch — Update the timestamp of a file or directory.
Источник