- 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
- 5 Commands to View the Content of a File in Linux Command Line
- 5 commands to view files in Linux
- 1. Cat
- 3. Less
- 4. Head
- 5. Tail
- Bonus: Strings command
- Команда cat Linux
- Команда cat
- Использование cat в Linux
- Выводы
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:
Источник
5 Commands to View the Content of a File in Linux Command Line
If you are new to Linux and you are confined to a terminal, you might wonder how to view a file in the command line.
Reading a file in Linux terminal is not the same as opening file in Notepad. Since you are in the command line mode, you should use commands to read file in Linux.
Don’t worry. It’s not at all complicated to display a file in Linux. It’s easy as well essential that you learn how to read files in the line.
Here are five commands that let you view the content of a file in Linux terminal.
5 commands to view files in Linux
Before you how to view a file in Unix like systems, let me clarify that when I am referring to text files here. There are different tools and commands if you want to read binary files.
1. Cat
This is the simplest and perhaps the most popular command to view a file in Linux.
Cat simply prints the content of the file to standard display i.e. your screen. It cannot be simpler than this, can it?
cat displays the content of the file on the screen
Cat becomes a powerful command when used with its options. I recommend reading this detailed tutorial on using cat command.
The problem with cat command is that it displays the text on the screen. Imagine if you use cat command with a file that has 2000 lines. Your entire screen will be flooded with the 200 lines and that’s not the ideal situation.
So, what do you do in such a case? Use less command in Linux (explained later).
The nl command is almost like the cat command. The only difference is that it prepends line numbers while displaying the text in the terminal.
nl command displays text with line numbers
There are a few options with nl command that allows you to control the numbering. You can check its man page for more details.
3. Less
Less command views the file one page at a time. The best thing is that you exit less (by pressing q), there are no lines displayed on the screen. Your terminal remains clean and pristine.
I strongly recommend learning a few options of the Less command so that you can use it more effectively.
There is also more command which was used in olden days but less command has more friendly features. This is why you might come across the humorous term ‘less is more’.
4. Head
Head command is another way of viewing text file but with a slight difference. The head command displays the first 10 lines of a text file by default.
You can change this behavior by using options with head command but the fundamental principle remains the same: head command starts operating from the head (beginning) of the file.
5. Tail
Tail command in Linux is similar and yet opposite to the head command. While head command displays file from the beginning, the tail command displays file from the end.
By default, tail command displays the last 10 lines of a file.
Head and Tail commands can be combined to display selected lines from a file. You can also use tail command to see the changes made to a file in real time.
Bonus: Strings command
Okay! I promised to show only the commands for viewing text file. And this one deals with both text and binary files.
Strings command displays the readable text from a binary file.
No, it doesn’t convert binary files into text files. If the binary file consists of actual readable text, strings command displays those text on your screen. You can use the file command to find the type of a file in Linux.
Conclusion
Some Linux users use Vim to view the text file but I think that’s overkill. My favorite command to open a file in Linux is the less command. It leaves the screen clear and has several options that makes viewing text file a lot easier.
Since you now know ways to view files, maybe you would be interested in knowing how to edit text files in Linux. Cut and Paste are two such commands that you can use for editing text in Linux terminal. You may also read about creating files in Linux command line.
Источник
Команда 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 и как ею пользоваться. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Источник