Learn Unix Cat Command with Examples:
The cat command is perhaps the most commonly used Unix command. It is derived from catenate – which describes the process of connecting things.
The cat command is a filter that can be used for multiple purposes:
- Display the contents of text files.
- Copy text files into a new file.
- Append a text file to the end of another text file.
Unix Cat command with Examples
Cat Command Syntax:
cat [options] [files]
The cat command becomes a very powerful tool when combined with the Unix shell’s input and output redirection symbols:
- cmd > file.txt: the “>” symbol redirects the stdout stream from the command to replace the contents of the specified file. The file will be created if it doesn’t exist, or its contents will be replaced if it does.
- cmd >> file.txt: the “>>” symbol redirects the stdout stream from the command to append to the contents of the specified file. The file will be created if it doesn’t exist, or the new contents will be appended to the same file if it does.
List contents of file1 on stdout
$ cat file1
List the contents of file1 and file2 together on stdout
$ cat file1 file2
Copy contents of file1 and file2 to file3
$ cat file1 file2 > file3
Append contents of file1 and file2 to file4
$ cat file1 file2 >> file4
If no filename is provided to the command, or if the file name is “-“, it reads the input text from stdin. This can be used to populate the contents of the file from the command prompt.
$ cat > file1 Hello World ^D
In this example, the command reads its input from the terminal, and writes the output to the file “file1”. The user can enter their text line by line and terminate the input with the “^D” character that indicates end-of-file.
The cat command also supports the following options:
- cat -n: number the output lines.
- cat -s: suppress repeated output lines that are empty.