This post will guide you how to copy a specified file to another file from the command line using cp command in Linux Operating system. How to I backup a file before modifying a file at the shell prompt using cat command in your Linux system.
Assuming that you have a file called myfile1 in your current working directory, and you want to copy this file to another file called myfile2, how to do it. You can use cp command to copy the first file’s content to another file in Linux.
- Cp Command
- Cat Command
- Copying a File to Another File Using Cp Command
- Copying a File to Another File using Cat Command
Cp Command
Cp command can be used to copy files and directories from SOURCe to dEST or multiple SOURCES to DIRECTORY.
The syntax of the Cp command are as followss:
cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE...
Cat Command
Cat command can be used to concatenate files and print on the standard output.
The syntax of the cat command is as follows:
cat [OPTION]... [FILE]...
Copying a File to Another File Using Cp Command
If you want to copy a file to another file in Linux, and you can type the following cp command at the shell prompt:
$ sudo cp myfile1 myfile2
Outputs:
[devops@mydevops ~]$ cp myfile1 myfile2 [devops@mydevops ~]$ ls myfile2 myfile2 [devops@mydevops ~]$ diff myfile1 myfile2
From the above outputs, you can see that myfile2 is a copy of the file myfile1, as they have the same content, and just have different file name.
Copying a File to Another File using Cat Command
You can also use another command called cat command to copy a file content to another file from the command line in your Linux system. type:
$ cat myfile1> myfile2
Outputs:
[devops@mydevops ~]$ cat myfile1 > myfile2 [devops@mydevops ~]$ [devops@mydevops ~]$ cat myfile1 this is file1 [devops@mydevops ~]$ cat myfile2 this is file1
If you want to append the content of myfile1 to another file myfile2, and you can type the following command:
$ cat myfile1 >> myfile2
Outputs:
[devops@mydevops ~]$ cat myfile1 this is file1 [devops@mydevops ~]$ cat myfile2 this is file2 [devops@mydevops ~]$ cat myfile1 >>myfile2 [devops@mydevops ~]$ cat myfile2 this is file2 this is file1
Conclusion
You should know that how to write or copy contents of a file to another file using cp/cat commands from the command line in your CentOS or RHEL or Ubuntu system.