copy two files at a time

What to do if I want to copy two file at a time using command ? let's say I have one folder named ABC and files are

mno.txt
xyz.txt
abcd.txt
qwe.txt and so on (100 no. of files)

Now I want to cp mno.txt and xyz.txt at a time . How can I do this ?


Solution 1:

Assuming you want to cp files into a directory, you can use the usual syntax for cp:

cp mno.txt xyz.txt destination_directory

Or use brace expansion for brevity:

cp {mno,xyz}.txt destination_directory

For the sake of clarity, it is better to use the -t (--target-directory) option of cp, this is GNU-ism:

cp -t destination_directory {mno,xyz}.txt

Just to note, if you want to cp the contents of multiple files with one go of cp, you can't. cp deals with one file at a time when copying contents of one file to another.

Solution 2:

Use cp -t destination_dir/ file1 file2 syntax.

Example:

bash-4.3$ ls dir1
file1  file2  file3
bash-4.3$ ls dir2/
bash-4.3$ cp -t dir2/  dir1/file1 dir1/file2
bash-4.3$ ls dir2
file1  file2

Addition to original answer.

The uses who like to play with python , may be interested in the following script, which allows copying arbitrary number of files specified on command line, with last argument being the destination.

Demo:

bash-4.3$ ls dir1
file1  file2  file3
bash-4.3$ ls dir2
bash-4.3$ ./copyfiles.py dir1/file1 dir1/file2 dir2
bash-4.3$ ls dir2
file1  file2

Script itself:

#!/usr/bin/env python3
from shutil import copyfile
from os import path
from sys import argv

new_dir = path.realpath(argv[-1])
for f in argv[1:-1]:
    base = path.basename(f)
    orig_file = path.realpath(f)
    new_file = path.join(new_dir,base)
    copyfile(orig_file,new_file)

Solution 3:

if you want to copy them at the same location (not to a new directory) to make backups, (for example), you can use a very small for loop to copy them with new names (here adding a .bak extension)

for f in {mno,xyz}.txt; do cp -- "$f" "$f".bak; done

{brace expansion} is the most succinct way to specify the particular files in your example, but you can use any suitable shell wildcards/globbing, or list out the files if necessary: for f in foo bar baz;

Solution 4:

You can do like this:

cp {mno,xyz}.txt /path/to/destination

Or if you need all .txt files:

cp {*}.txt /path/to/destination