Bash: How to Copy and Rename a File


Often you may want to copy and rename a file in Bash.

You can use the following methods to do so:

Method 1: Copy and Rename File in Same Folder

cp my_file.txt my_file_copy.txt

This particular example makes a copy of the file named my_file.txt and renames it my_file_copy.txt within the same folder.

Method 2: Copy and Rename File to Different Folder

cp my_file.txt /c/users/bobbi/data2/folder2/my_file_copy.txt

This particular example makes a copy of the file named my_file.txt and copies it to a new folder named folder2 and renames it my_file_copy.txt.

Note: The cp command allows you to “copy” one or more files to another location.

The following examples show how to use each method in practice.

Example 1: How to Copy and Rename File in Same Folder

Suppose that our current folder is named folder1.

We can use the ls command to view all of the files in this folder:

Suppose that we would like to make a copy of the file named cities.txt and rename it cities_copy.txt.

We can use the following syntax to do so:

cp cities.txt cities_copy.txt

The following screenshot shows how to use this syntax in practice:

Bash copy and rename file

Notice that when we use the ls command again to view the contents of folder1 we can see that a copy of the cities.txt file has been made with a new name of cities_copy.txt.

Example 2: How to Copy and Rename File to Different Folder

Suppose that we would like to make a copy of the cities.txt file from folder1 and copy it to a new folder named folder2 with a new name of cities_copy.txt.

We can use the following syntax to do so:

cp cities.txt /c/users/bobbi/data2/folder2/cities_copy.txt

The following screenshot shows how to use this syntax in practice:

Bash copy and rename file to another folder

Notice that when we use the ls command to view all files in the folder named folder2 we can see that a copy of the original cities.txt file has been made and it is named cities_copy.txt.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Copy Multiple Specific Files from One Folder to Another
Bash: How to Copy All Files in Directory to Another Directory
Bash: How to Rename Extension of Multiple Files

Leave a Reply