Cat how to linux

How To Use cat Command In Linux / UNIX

It can be used for the following purposes:

  • Display text files on screen.
  • Copy text files.
  • Combine text files.
  • Create new text files.

cat command Syntax

The syntax is as follows:

Displaying The Contents of Files

To read or read the contents of files, enter:
$ cat /etc/passwd
The above command will display the contents of a file named /etc/passwd. By default cat will send output to the monitor screen. But, you can redirect from the screen to another command or file using redirection operator as follows:
$ cat /etc/passwd > /tmp/test.txt
In the above example, the output from cat command is written to /tmp/test.txt file instead of being displayed on the monitor screen. You can view /tmp/test.txt using cat command itself:
$ cat /tmp/test.txt

Concatenate files

Concatenation means putting multiple file contents together. The original file or files are not modified or deleted. In this example, cat will concatenate copies of the contents of the three files /etc/hosts, /etc/resolv.conf, and /etc/fstab:
$ cat /etc/hosts /etc/resolv.conf /etc/fstab
You can redirect the output as follows using shell standard output redirection:
$ cat /etc/hosts /etc/resolv.conf /etc/fstab > /tmp/outputs.txt
$ cat /tmp/outputs.txt
You can also use a pipe to filter data. In this example send output of cat to the less command using a shell pipe as the file is too large for all of the text to fit on the screen at a time:
$ cat /etc/passwd | less

How Do I Create a File?

To create a file called foo.txt, enter:
$ cat > foo.txt
Sample outputs:

To save and exit press the CONTROL and d keys (CTRL+D). Please note that if a file named foo.txt already exists, it will be overwritten. You can append the output to the same file using >> operator:
$ cat >> bar.txt
The existing bar.txt file is preserved, and any new text is added to the end of the existing file called bar.txt. To save and exit press the CONTROL and d keys (CTRL+D).

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How Do I Copy File?

The cat command can also be used to create a new file and transfer to it the data from an existing file. To make copy of
$ cat oldfile.txt > newfile.txt
To output file1’s contents, then standard input, then file2’s contents, enter:
$ cat file1 — file2
A hyphen indicates that input is taken from the keyboard. In this example, to create a new file file2 that consists of text typed in from the keyboard followed by the contents of file1, enter:
$ cat — file1 > file2

Читайте также:  Подключить сетевой диск windows 10 что это

cat command options

To number non-blank output lines, enter (only works with GNU cat command version):
$ cat -b /etc/passwd
Sample outputs:

To number all output lines, enter (GNU cat version only):
$ cat -n /etc/passwd
To squeeze multiple adjacent blank lines, enter (GNU cat version only):
$ cat -s /etc/passwd
To display all nonprinting characters as if they were visible, except for tabs and the end of line character, enter (GNU cat version only):
$ cat -v filename

cat Command Abuse

The main purpose of cat is to catenate files. If it’s only one file, concatenating it with nothing at all is a waste of time, and costs you a process. For example,
$ cat /proc/cpuinfo | grep model
Can be used as follows:
$ grep model /proc/cpuinfo
Another example,
cat filename | sed -e ‘commands’ -e ‘commands2’
Can be used as follows which is cheaper:
sed sed -e ‘commands’ -e ‘commands2’ filename
See useless use of cat command for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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.

Читайте также:  Сертификат для установки windows

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 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
  • » Syntax
  • » Examples
  • » View A File
  • » Create A File
  • » Cat and Pipes
  • » Combine Files
  • » Append To A File
  • » Number All Lines
  • » Non-printing Characters
  • » View Large Number Of Files
  • » Print Files
  • » Joining Binary Files
  • » Fooling Programs
  • » Testing Audio Device
  • » Gathering Linux System Information
  • » Display Large Blocks of Textual Data In A Script
  • » Print Files In Reverse
  • » Options
  • » Summing up

The cat command is used for:

  1. Display text file on screen
  2. Read text file
  3. Create a new text file
  4. File concatenation
  5. Modifying file
  6. Combining text files
  7. 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:

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 и как ею пользоваться. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!

Источник

Читайте также:  Bluetooth виджеты для windows 10
Оцените статью