What is cat
cat command can be used to concatenate, copy, create new file and print the content of files. You cannot edit files which are already existing in system with cat command.
Syntax of cat command
cat [options] [file]
Examples of cat command
- Display file content – To display / print on screen contents of a file, you can simply use cat followed by file name.
if this file is longer to fit in single screen cat will directly reach to end of text file.
- Use Cat Command with More & Less Options – If a file is longer to fit in single screen cat will directly reach to end of text file. In such a case you can use more or less commands in conjunction with cat command.
cat text.txt | more cat text.txt | less
This will create an output where you can view content page by page.
- Display file contents with line numbers – To display line numbers of content of file you can use -n option
cat -n text.txt
This can pretty useful if you are displaying a script / list of files/ list of items etc.
- Display multiple files with single command – cat command can also be used to display multiple files in one go. You can type cat command followed by file names.
cat text1.txt text2.txt
The above command will display multiple file with single command
- Create a file – Another basic use of cat command where you can create a file using cat command followed entering content of file
cat > text1.txt
To save content and terminate command you will have to press control+D simultaneously
- Create copy of a file – To copy file use > (greater than)
cat text.txt > text1.txt
This command will copy contents of file text to text1.
Note: Use this option carefully as contents of file text 1 will be overwritten when you are using this command.
- Copy content of multiple Files in a Single File – To copy content of multiple files again use of > (greater than) is done.
cat text text1 text2 > text3
This command will copy contents of file text, text1 and text 2 to text 3 file. Note: Use this option carefully, as contents of file text 3 are overwritten while using this command.
- Append contents to a file – To append contents one file to another file, you will have to use >> symbol (greater than types twice) along with file names in cat command as shown in syntax below.
cat text.txt >> text1.txt
This command will add contents of file text to end of file text1.
- Show end of line – Use of –e is done to shows end of line. This option of cat command will add an $ symbol at end of each line.
cat –e text.txt