Linux copy file with new name

Linux Copy File Command [ cp Command Examples ]

cp Command Syntax

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Terminal app/Shell prompt
Est. reading time 3 mintues

The syntax is as follows to copy files and directories using the cp command:
cp SOURCE DEST
cp SOURCE DIRECTORY
cp SOURCE1 SOURCE2 SOURCE3 SOURCEn DIRECTORY
cp [OPTION] SOURCE DEST
cp [OPTION] SOURCE DIRECTORY
Where,

  • In the first and second syntax you copy SOURCE file to DEST file or DIRECTORY.
  • In the third syntax you copy multiple SOURCE(s) (files) to DIRECTORY.

Note: You need to type the cp command at the dollar sign ($) prompt. This prompt means that the shell is ready to accept your typed commands. Do not type the dollar ($) sign. You need to open the Terminal app to use cp command on a Linux.

Linux Copy File Examples

To make a copy of a file called file.doc in the current directory as newfile.doc, enter:
$ cp file.doc newfile.doc
$ ls -l *.doc
Sample outputs:

You can copy multiple files simultaneously into another directory. In this example, copy the files named main.c, demo.h and lib.c into a directory named backup:
$ cp main.c demo.h libc. backup
If backup is located in /home/project, enter:
$ cp main.c demo.h libc. /home/project backup

Copy a file to another directory

To copy a file from your current directory into another directory called /tmp/, enter:
$ cp filename /tmp
$ ls /tmp/filename
$ cd /tmp
$ ls
$ rm filename

Verbose option

To see files as they are copied pass the -v option as follows to the cp command:

Preserve file attributes

To copy a file to a new file and preserve the modification date, time, and access control list associated with the source file, enter:
$ cp -p file.txt /dir1/dir2/
$ cp -p filename /path/to/new/location/myfile
This option ( -p ) forces cp to preserve the following attributes of each source file in the copy as allowed by permissions:

  1. Modification time/date
  2. Access time
  3. File flags
  4. File mode
  5. User ID (UID)
  6. Group ID (GID)
  7. Access Control Lists (ACLs)
  8. Extended Attributes (EAs)

Copying all files

The star wildcard represents anything i.e. all files. To copy all the files in a directory to a new directory, enter:
$ cp * /home/tom/backup

The star wildcard represents anything whose name ends with the .doc extension. So, to copy all the document files (*.doc) in a directory to a new directory, enter:
$ cp *.doc /home/tom/backup

Recursive copy

To copy a directory, including all its files and subdirectories, to another directory, enter (copy directories recursively):
$ cp -R * /home/tom/backup

Linux copy file command with interactive option

You can get prompt before overwriting file. For example, if it is desired to make a copy of a file called foo and call it bar and if a file named bar already exists, the following would prompt the user prior to replacing any files with identical names:
cp -i foo bar

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Verbose output with cp command

If you pass the -v to the cp, it makes tells about what is going on. That is verbose output:
cp -v file1 file2
cp -avr dir2 /backups/

Conclusion

This page explained cp command that is used for copying files under Linux and Unix-like systems. For more info see man pages: ls(1).

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Copying and renaming files on Linux

There’s more to copying and renaming files on Linux than cp and mv. Try some commands and strategies that might surprise you and save you some time.

Linux users have for many decades been using simple cp and mv commands to copy and rename files. These commands are some of the first that most of us learned and are used every day by possibly millions of people. But there are other techniques, handy variations, and another command for renaming files that offers some unique options.

First, let’s think about why might you want to copy a file. You might need the same file in another location or you might want a copy because you’re going to edit the file and want to be sure you have a handy backup just in case you need to revert to the original file. The obvious way to do that is to use a command like “cp myfile myfile-orig”.

If you want to copy a large number of files, however, that strategy might get old real fast. Better alternatives are to:

  • Use tar to create an archive of all of the files you want to back up before you start editing them.
  • Use a for loop to make the backup copies easier.

The tar option is very straightforward. For all files in the current directory, you’d use a command like:

For a group of files that you can identify with a pattern, you’d use a command like this:

In each case, you end up with a myfiles.tar file that contains all the files in the directory or all files with the .txt extension.

An easy loop would allow you to make backup copies with modified names:

When you’re backing up a single file and that file just happens to have a long name, you can rely on using the tab command to use filename completion (hit the tab key after entering enough letters to uniquely identify the file) and use syntax like this to append “-orig” to the copy.

You then have a file-with-a-very-long-name and a file-with-a-very-long-name file-with-a-very-long-name-orig.

Renaming files on Linux

The traditional way to rename a file is to use the mv command. This command will move a file to a different directory, change its name and leave it in place, or do both.

But we now also have the rename command to do some serious renaming for us. The trick to using the rename command is to get used to its syntax, but if you know some perl, you might not find it tricky at all.

Here’s a very useful example. Say you wanted to rename the files in a directory to replace all of the uppercase letters with lowercase ones. In general, you don’t find a lot of file with capital letters on Unix or Linux systems, but you could. Here’s an easy way to rename them without having to use the mv command for each one of them. The /A-Z/a-z/ specification tells the rename command to change any letters in the range A-Z to the corresponding letters in a-z.

You can also use rename to remove file extensions. Maybe you’re tired of seeing text files with .txt extensions. Simply remove them — and in one command.

Now let’s imagine you have a change of heart and want to put those extensions back. No problem. Just change the command. The trick is understanding that the “s” before the first slash means “substitute”. What’s in between the first two slashes is what we want to change, and what’s in between the second and third slashes is what we want to change it to. So, $ represents the end of the filename, and we’re changing it to “.txt”.

You can change other parts of filenames, as well. Keep the s/old/new/ rule in mind.

Note in the examples above that when we use an s as in «s/old/new/», we are substituting one part of the name with another. When we use y, we are transliterating (substituting characters from one range to another).

Wrap-up

There are a lot of options for copying and renaming files. I hope some of them will make your time on the command line more enjoyable.

Sandra Henry-Stocker has been administering Unix systems for more than 30 years. She describes herself as «USL» (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she’s chasing the bears away from her bird feeders.

Источник

Copy files to another folder, use new name if exists

I have folders with almost same files and names in multiple locations and drives. I would like to move them all to a single location. The structure is something like below:

I would like to move them all to another single location on another drive. When copying or moving, I would like to rename the file being moved to something like FileN-copy-1.txt, etc. This is similar to the behaviour when you move files in finder on mac and it names the files incrementally if you select «Keep both».

I have tried using rsync but it does not seem to have an option where i can rename the new file being moved.

Any help would be greatly appreciated.

3 Answers 3

You can make simple bash script like this

so you enter searching and destination folder, and then run the script (before make it executable by

This script will look for files, and put them in variable (FlN) and cut variable to just file name without folders in front (FlNo), than copy if no file like this present. If present he will create a file with added -copy-X just before the ending of the file name (X is the number of copy). A variable $CpNum will be number of maximum copies of each file (can be safely increased) Currently works for .txt files, but you can modify it. You can further play to add option to call a script with argument, or make it to many different extensions

rsync is a good first choice if you want to copy all files and subdirectories under a directory. It does have an option for not overwriting files, the -b backup option.

However, by default the backup is using a naming scheme that’s not useful for this purpose (an added

character at the end of the filename, which some tools are hiding as unneeded backup files).

There is an option to change it ( —suffix newending ), which can be anything, but it’s still tacked on at the end, and not removing any previous extension. If that works for you, this is an easy job for rsync . Note that it’s a proper backup — files with the same names that are otherwise identical will not have two copies.

For example, in your case two commands would be needed to populate the destination from two sources:

Note the peculiar quoting required for the files with white spaces, and the ending / denoting the contents of the directory (starting under the directory, not including it).

Files that are already present from Folder 1 will be tacked on a -copy.txt such as:

Both commands essentially synchronise from the first directory to the second, and the additional command would indeed overwrite anything present in the destination, the backup option changes this so that the file that would otherwise be destroyed is kept as a backup. So indeed, the files from the second line would retain their names. This still might be useful for the original purpose if the commands were run in a different order.

Источник

How to Copy Files and Directories in Linux

Home » SysAdmin » How to Copy Files and Directories in Linux

This guide will show you how to copy files and directories in Linux by executing commands from the command line. Furthermore, the commands listed below detail how to create system-wide backups or filter out and copy only specific files.

Note: These Linux commands can only be run from a terminal window. If your version of Linux boots to a desktop graphical interface, launch a terminal window by pressing CTRL-ALT-F2 or CTRL-ALT-T.

Using the cp Command to Copy Files and Directories in Linux

The cp command is the primary method for copying files and directories in Linux. Virtually all Linux distributions can use cp . The basic format of the command is:

This Linux command creates a copy of the my_file.txt file and renames the new file to my_file2.txt.

By default, the cp command runs in the same directory you are working in. However, the same file cannot exist twice in the same directory. You’ll need to change the name of the target file to copy in the same location. Some users will add _old, some will add a number, and some will even change the three-letter extension (e.g., .bak instead of .txt).

You may not get a warning before Linux overwrites your file – be careful, or see below for the –i option.

Additional Options

Additional options can be used in combination with the cp command:

  • –v verbose: shows the progress of multiple copied files
  • –ppreserve: keeps the same attributes, like creation date and file permissions
  • –f force: force the copy by deleting an existing file first
  • –i interactive: prompts for confirmation, highly advised
  • –Rrecursive: copies all files and subfolders in a directory
  • –u update: copy only if source is newer than destination

Note: The -p (preserve) option forces the system to preserve the following source file attributes: modification time, access time, user ID (UID), group ID (GID), file flags, file mode, access control lists (ACLs), and extended attributes (EAs).

How to Copy File to Another Directory in Linux

To copy a file from the directory you’re working in to a different location, use the command:

You don’t need to rename the file unless there’s already one with the same name in the target directory.

To specify a path for the source file:

This lets you copy without having to change directories. The cp command will create the /new_directory if it doesn’t exist.

To rename and copy a file to a different path:

This option is useful for creating backups of configuration files, or for copying data to a storage device.

Note: Learn how to move directories in Linux.

Copy Multiple Files from One Directory to Another in Linux

You may need to copy more than one file at a time.

List each file to be copied before the target directory:

This example created a copy of all three files in the /new_directory folder.

Use a wildcard to specify all files that share a string of characters:

This would find all the files with the .jpg extension in the /pictures directory, and copy them into the /new_directory folder.

To copy an entire folder and its subfolders and files, use the –R option:

–R stands for recursive, which means “everything in that location.” This would copy all the files, as well as all the directories, to the /new_directory folder.

Copy Using rsync Command

The rsync command in Linux is used to synchronize or transfer data between two locations. Usage is similar to cp , but there are a few key differences to note.

To copy a single file, enter the following into a terminal:

  • The –a option means all, and is included with rsync commands – this preserves subdirectories, symbolic links, and other metadata.
  • Replace the my_file.txt file in the working directory.
  • Replace /new_directory/ with the destination.
  • Using my_file_backup.txt as the target indicates the file will be renamed during the copy.

To copy a directory with rsync, enter the following:

This copies the contents of the /etc/docker/ directory to /home/backup/docker/. Make sure to keep the slashes. Omitting the slash on the source directory will copy the contents into a subdirectory.

To omit files from being copied, check out our guide on how to exclude files and directories in data transfer using rsync command.

Other Options

The ls command is a handy partner to the cp command in Linux.

To list the contents of a directory enter the command:

The example above displays all the files in /directory. Use this command after copying to verify the files were copied successfully.

To change directories, use cd and the name of the directory. For example:

The command prompt will change to display that you’ve changed directories.

Now you understand how to copy files in Linux. The cp command is a versatile and powerful tool for managing and backing up files.

Источник

Читайте также:  Мониторинг локальной сети linux
Оцените статью