How To Use Cat Command.
In this article, we will show you how to use the cat command through practical examples.
cat Command Syntax
The cat utility expressions take the following form:
OPTIONS – cat options . Use cat –help to view all available options.
FILE_NAMES – Zero or more file names.
Displaying File Contents.
Redirect Contents of File.
Instead of displaying the output to stdout (on the screen), you can redirect it to a file.
The following command will copy the contents of music to my.music using the (>) operator :
If the my.musci file doesn’t exist, the command will create it. Otherwise, it will overwrite the file.
Use the (>>) operator to append the contents of music to my.music :
Same as before, if the file is not present, it will be created.
Print Line Numbers
To display contents of a file with line numbers, invoke cat with the -n option:
Suppress Repeated Empty Lines
-s option to omit the repeated empty output lines:
Display TAB characters
The -T option allows you to visually distinguish between tabs and spaces.
The TAB characters will be displayed as ^I.
Display End of Lines
To display the invisible line ending character use the -e argument:
The Line endings will be displayed as $.
When passing two or more file names as arguments to the cat command, the contents of the files will be concatenated. cat reads the files in the sequence given in its arguments and displays the file’s contents in the same sequence.
For example, the following command will read the contents of file1.txt and file2.txt and display the result in the terminal:
You can concatenate two or more text files and write them to a file.
The following command will concatenate the contents of file1.txt and file2.txt and write them to a new file combinedfile.txt using the (>) operator :
If the combinedfile.txt file doesn’t exist, the command will create it. Otherwise, it will overwrite the file.
To concatenate the contents of file1.txt and file2.txt and append the result to file3.txt to use the (>>) operator:
If the file is not present, it will be created.
When concatenating files with cat, you can use the same arguments as shown in the previous section.
Creating small files with cat it often easier than opening a text editor such as nano , Vim, Sublime Text , or Visual Studio Code .
To create a new file, use the cat command followed by the redirection operator (>) and the name of the file you want to create. Press Enter, type the text and once you are done, press the CRTL+D to save the file.
In the following example, we are creating a new file named my.fav_songs:
If a file named file1.txt is present, it will be overwritten. Use the ‘>>’ operator to append the output to an existing file.
The cat command can display, combine and create new files.