cat command
cat command is one of the basic linux commands used to concatenate and write files. cat command can be used for the following major purposes
To view a file type cat followed by filename or path to the file name
Syntax:
- View text files
- Create text files
- Append, Combine text files
- Copy a text file
Viewing a file
To view a file type cat followed by filename or path to the file name
Syntax:
cat filename
cat /path/to/file
cat /path/to/file
For example, to view /etc/shells file which contains the full pathnames of valid login shells enter the command as
cat /etc/shells
Sample Output:
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/bash
/sbin/nologin
/bin/dash
Creating a file
In order to create a text file use the following syntax
cat > filename
Usage:
cat > demo.txt
The cursor will go to the next line instead of the prompt. Now type the text to be entered.
Hello World !!!!
This is a demo file
[cntrl+D]
Once the entries are made go to a new line and press control key and d keys together to quit. A new text file demo.txt will be created containing the texts entered. Verify the file with cat command (i.e. cat demo.txt)This is a demo file
[cntrl+D]
Combining Files
cat command can be used to combine two or more files to a single fileUsage:
cat file1.txt file2.txt file3.txt > file123.txt
In the above example file1.txt file2.txt and file3.txt are 3 different text files and they are combined together using cat command to create a new file file123.txt. Verify the file with cat command (i.e. cat file123.txt)Appending Files
cat command can be used append additional data to an already existing file.
Syntax:
cat >> filename
The method is almost similar to that of creating a new file except we are using double greater-than symbol (>>) instead of greater-than symbol (>). To append data to the file enter
cat >> demo.txt
Type the text in the new line
To err is human.. to really foul up requires the root password
[cntrl+d]
[cntrl+d]
The data will be appended. If greater-than sign (>) is used instead of double greater-than sign (>>) the file will be overwritten. ie the new data will replace the existing data contained in the file. Verify the file with cat command (i.e. cat demo.txt)
Copy Files
cat command can be used to copy the contents of a file to another file
Syntax:
cat file1.txt > file2.txt
Here the contents of file1.txt is copied to file2.txt i.e. Output of cat file1.txt is re-directed to file2.txtThese are the cat command's most commonly used methods. There are so many ways the commands can be used based on your requirements and that's the beauty of linux. For additional info and usages check the cat man page.
Comments
Post a Comment