-1

Let's say I have two directories: orig and backup. Orig contains the file foo. I want to copy the file foo to the backup directory, but with the extension .txt.

  • If you are copying to the same file-system, it is not a backup. What you, probably, want is revision-control. – ctrl-alt-delor Feb 23 at 18:47
1
cp /path/to/orig/foo /path/to/backup/foo.txt

cp takes the source file as its first parameter and the destination file as its second parameter. You may be used to simply specifying the destination directory, which is allowed, but you can also specify the full path in order to rename the destination file at the same time.


The cp command has two ways of being invoked, with a source file and a target directory, and with a source file and a target file. This is reflected by the command's synopsis section in the manual (man cp):

usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory
0

The secret is realising that there are no file-name-extensions. File-name-extensions is a CP/M concept, that was adopted in to MS_DOS (a poor clone of CP/M). Unix does not have them, it is just part of the name. There are, however, tools to help with this.

  • basename: can be used to get the basename (without suffix).
  • rename: (the Larry Wall version) is good for renaming files.

For what you want.

( fileName=foo; cp -T "/path/to/orig/${fileName}" "/path/to/backup/${fileName}.txt" )

For safety I added the -T option, it can be omitted (not all cps have it. However if you make an error (specify a directory in the 2nd argument), then without it, it will copy the file to the directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.