- 📑 Команда cat и примеры её использования в Linux
- Общий синтаксис команды Cat
- 1. Отобразить содержимое файла
- 2. Просмотр содержимого нескольких файлов в терминале
- 3. Создание файла с помощью команды Cat
- 4. Использование команды Cat с опциями more и less
- 5. Отображение номеров строк в файле с помощью cat
- 6. Отображение $ в конце строки и вместо пробелов между абзацами
- 7. Отображение нескольких файлов одновременно
- 8. Перенаправление стандартного вывода оператора cat.
- 9. Добавление содержимого файла в существующий файл
- 10. Перенаправление нескольких файлов в один файл
- 11. Сортировка содержимого нескольких файлов в одном файле
- 13 Basic Cat Command Examples in Linux
- General Syntax of Cat Command
- 1. Display Contents of File
- 2. View Contents of Multiple Files in terminal
- 3. Create a File with Cat Command
- 4. Use Cat Command with More & Less Options
- 5. Display Line Numbers in File
- 6. Display $ at the End of File
- 7. Display Tab Separated Lines in File
- 8. Display Multiple Files at Once
- 9. Use Standard Output with Redirection Operator
- 10. Appending Standard Output with Redirection Operator
- 11. Redirecting Standard Input with Redirection Operator
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Команда cat Linux
- Команда cat
- Использование cat в Linux
- Выводы
- Cat command in Linux with examples
- 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 (сокращение от «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 будет передан для сортировки, а результат будет перенаправлен во вновь созданный файл.
Источник
13 Basic Cat Command Examples in Linux
The cat (short for “concatenate“) command is one of the most frequently used commands in Linux/Unix-like operating systems. cat command allows us to create single or multiple files, view content of a file, concatenate files and redirect output in terminal or files.
In this article, we are going to find out the handy use of cat commands with their examples in Linux.
General Syntax of Cat Command
1. Display Contents of File
The below example will show the contents of /etc/passwd file.
2. View Contents of Multiple Files in terminal
In below example, it will display the contents of the test and test1 file in the terminal.
3. Create a File with Cat Command
We will create a file called test2 file with the below command.
Awaits input from the user, type desired text, and press CTRL+D (hold down Ctrl key and type ‘d‘) to exit. The text will be written in the test2 file. You can see the content of the file with the following cat command.
4. Use Cat Command with More & Less Options
If a file having a large number of content that won’t fit in the output terminal and the screen scrolls up very fast, we can use parameters more and less with the cat command as shown below.
5. Display Line Numbers in File
With the -n option you could see the line numbers of a file song.txt in the output terminal.
6. Display $ at the End of File
In the below, you can see with the -e option that ‘$‘ is shows at the end of the line and also in space showing ‘$‘ if there is any gap between paragraphs. This option is useful to squeeze multiple lines into a single line.
7. Display Tab Separated Lines in File
In the below output, we could see TAB space is filled up with the ‘^I‘ characters.
8. Display Multiple Files at Once
In the below example we have three files test, test1, and test2, and able to view the contents of those files as shown above. We need to separate each file with ; (semicolon).
9. Use Standard Output with Redirection Operator
We can redirect the standard output of a file into a new file else existing file with a ‘>‘ (greater than) symbol. Careful, existing contents of the test1 will be overwritten by the contents of the test file.
10. Appending Standard Output with Redirection Operator
Appends in existing file with ‘>>‘ (double greater than) symbol. Here, the contents of the test file will be appended at the end of the test1 file.
11. Redirecting Standard Input with Redirection Operator
When you use the redirect with standard input ‘ Tags cat command Examples
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Команда 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 и как ею пользоваться. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
Cat command in Linux with examples
Cat(concatenate) command is very frequently used in Linux. It reads data from the file and gives their content as output. It helps us to create, view, concatenate files. So let us see some frequently used cat commands.
1) To view a single file
Command:
2) To view multiple files
Command:
3) To view contents of a file preceding with line numbers.
Command:
4) Create a file
Command:
5) Copy the contents of one file to another file.
Command:
6) Cat command can suppress repeated empty lines in output
Command:
7) Cat command can append the contents of one file to the end of another file.
Command:
8) Cat command can display content in reverse order using tac command.
Command:
9) Cat command can highlight the end of line.
Command:
10) If you want to use the -v, -E and -T option together, then instead of writing -vET in the command, you can just use the -A command line option.
Command
11) Cat command to open dashed files.
Command:
12) Cat command if the file has a lot of content and can’t fit in the terminal.
Command:
12) Cat command to merge the contents of multiple files.
Command:
13) Cat command to display the content of all text files in the folder.
Command:
14) Cat command to write in an already existing file.
Command :
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Источник
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:
Источник