Copying and renaming files on Linux



Copying and renaming files on Linux

Nana B Agyei

(CC BY 2.0)

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:

$ tar cf myfiles.tar *

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

$ tar cf myfiles.tar *.txt

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:

$ for file in *
> do
>    cp $file $file-orig
> done

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.

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.