Linux is a file-based operating system and in daily operation, we use the copy and rename operations lots of times. There are different commands and methods to copy and rename files in Linux. The cp
command is used to copy file and mv
command is used to rename files. Actually only the cp command can be used to copy and rename a file if we want to copy a file and rename it because the copied files are also renamed automatically.
Copy and Rename Files with cp Command
The cp
command is used to copy files but as we expect it also renames the copied files with the specified name. The source file is specified as the first parameter and the destination file with a new name is specified as the second parameter. In the following example, we copy and rename the file named db.txt into newdb.txt .
$ cp db.txt newdb.txt
We can also copy and rename multiple files with a single command execution. In the following example, we copy and rename files users.txt, db.txt, groups.txt.
$ cp db.txt newdb.txt; cp users.txt newusers.txt; cp groups.txt newgroups.txt;
Rename File with mv Command
If we only need to rename a file we can use the mv command. The mv command is actually created to move files but it can be used to rename files which are very similar to moving files with new names. In the following example, we rename the file db.txt .
$ mv db.txt newdb.txt
Copy and Rename Files with cp and rename Command
The rename
command is created to rename files. We can use the cp and rename commands in order to copy and rename files. The cp can be used to copy single or multiple files. In the following example, we copy all files from the /home/db to the current working directory and rename them with the rename command by changing their names.
cp /home/db .
rename 's/$/.db/' *
Copy and Rename Specific File Extensions
The rename command can be used to copy and rename files with specific extensions. In the following example, we rename all files with the *.txt
extension into the *.t
extension.
cp /home/db .
rename 's/$/.t/' *.txt