Linux copy file to multiple files

Linux commands to copy one file to many files

@J.F.Sebastian: Yeah, but since the OP clearly wants this to work for more than just two destination files, I went with the form that highlights the support for that. Maybe I should have written tee file2 file3 file4 and dispensed with the two-file parallelism?

Not sure if this is still relevant, but I just want to note that using the tee solution, would not preserve the initial files rights.

@bioShark: Right — it only copies the contents of the files. That’s why I described it as «a slightly looser sense of ‘copy'».

But there’s a little typo. Should be:

And as mentioned above, that doesn’t copy permissions.

You can improve/simplify the for approach (answered by @ruakh) of copying by using ranges from bash brace expansion:

for f in file; do cp file $f; done 

This copies file into file1, file2, . file10 .

for FILE in "file2" "file3"; do cp file1 $FILE; done 

To copy the content of one file (fileA.txt) to many files (fileB.txt, fileC.txt, fileD.txt) in Linux,

use the following combination cat and tee commands:

cat fileA.txt | tee fileB.txt fileC.txt fileD.txt >/dev/null 
  • applicable to any file extensions
  • only file names and extensions change, everything else remains same.
file=$1 shift for dest in "$@" ; do cp -r $file $dest done 

cat file1 | tee file2 | tee file3 | tee file4 | tee file5 >/dev/null

It probably works, but its is pretty inflexible. And it will likely be inefficient if you are copying large files.

Use something like the following. It works on zsh.

cat file > firstCopy > secondCopy > thirdCopy

cat file > — for filenames with numbers.

You should use the cp script mentioned earlier for larger files.

I’d recommend creating a general use script and a function (empty-files), based on the script, to empty any number of target files.

Name the script copy-from-one-to-many and put it in your PATH.

#!/bin/bash -e # _ _____ # | |___ /_ __ # | | |_ \ \/ / Lex Sheehan (l3x) # | |___) > < https://github.com/l3x # |_|____/_/\_\ # # Copy the contents of one file to many other files. source=$1 shift for dest in "$@"; do cp $source $dest done exit 

NOTES

The shift above removes the first element (the source file path) from the list of arguments ( "$@" ).

Examples of how to empty many files:

Create file1, file2, file3, file4 and file5 with content:

for f in file; do echo $f > "$f"; done 

Empty many files:

copy-from-one-to-many /dev/null file1 file2 file3 file4 file5 

Empty many files easier:

# Create files with content again for f in file; do echo $f > "$f"; done copy-from-one-to-many /dev/null file

Create empty_files function based on copy-from-one-to-many

Example usage

# Create files with content again for f in file; do echo $f > "$f"; done # Show contents of one of the files echo -e "file3:\n $(cat file3)" empty_files file # Show that the selected file no longer has contents echo -e "file3:\n $(cat file3)" 

Don't just steal code. Improve it; Document it with examples and share it. - l3x

Here's a version that will preface each cp command with sudo:

#!/bin/bash -e # Filename: copy-from-one-to-may # _ _____ # | |___ /_ __ # | | |_ \ \/ / Lex Sheehan (l3x) # | |___) > < https://github.com/l3x # |_|____/_/\_\ # # Copy the contents of one file to many other files. # Pass --sudo if you want each cp to be perfomed with sudo # Ex: copy-from-one-to-many $(mktemp) /tmp/a /tmp/b /tmp/c --sudo if [[ "$*" == *--sudo* ]]; then maybe_use_sudo=sudo fi source=$1 shift for dest in "$@"; do if [ $dest != '--sudo' ]; then $maybe_use_sudo cp $source $dest fi done exit 

Источник

Читайте также:  Linux all groups command

How do I Copy Multiple Files Using CP in Linux

CP allows you to copy directories and command files using the command line. With this command, you can transfer multiple files or folders, preserve attribute information and create their backups. CP copies file independently from their originals. So, we can say that the CP command is useful for Linux. People still don’t know how to use this command and search for answers regarding copying multiple files using CP in Linux. That’s why we have written this article to briefly describe how to copy multiple files using CP in Linux.

How do I Copy Multiple Files Using CP in Linux?

Now we will explain different methods to use CP for performing various tasks.

Copy a File Using CP Command

The file, which we will copy with the cp command, passes its name and destination. We will copy the Linuxhint.txt file to a new file named Linuxhintteam.txt using the cp command. During the operation, the cp command will also create a new file part of the operation.

First, select a folder/directory in which the file is available. In our case, the file is available in the Documents directory, so we use the following command:

After using the ls command to display the available file in the directory.

Now, execute the below command to make a copy of a specific file:

Here we have used the below command to make a copy of the Linuxhint.txt file:

To verify that the file is successfully copied, use the ls command again.

Copy Multiple Files Using CP Command

You must provide both the file name and the destination directory when using the cp command to copy multiple files.

First, open the specific directory in the terminal and execute the tree command. If you don’t know about the tree command, then please check out this blog.

In the Documents folder, we have two files, i.e., Linuxhint.txt and Linuxhintteam.txt, and one folder named Linuxtricks. Now, execute the below command in the terminal:

Here we used the following command to copy Linuxhint.txt and Linuxhintteam.txt in the Linuxtricks folder:

To verify that the files are copied, use the tree command again.

Copy a Directory Using CP Command

The CP command, by default, does not copy directories. On copying the directory, it shows an error.

To copy the directory with the help of the cp command, we have to pass -R flag. It creates a copy by copying the flagged folder recursively.

Here we have used the following command to copy the directories:

Finally, execute the tree command to verify that the system has successfully created multiple directories.

Copy Multiple Directories Using CP Command

To copy the multiple directories with the cp command, copy the path of the directories and pass it after the destination directory.

Читайте также:  Astra linux сетевое администрирование

First, execute the tree command to see details about files and folders available in the directory:

Now execute the below command to copy multiple directories using the CP command:

Here we used the following command to copy Linuxtips and Linuxtricks into the LinuxOS folder:

Finally, we verified that the system copied the directories correctly.

Take a Backup when Copying a File

We can use the -b flag to back up the file if someone overwrites the copied file. It also creates a backup file by copying the file in place.

ls
Filename.txt Filename1.txt
cp -b Filename.txt Filename1.txt
ls
Filename.txt Filename1.txt Filename1.txt~

In the above example, Linuxhintteam.txt ~ represents the backup file.

Prompt for Confirmation when Copying a File

We can use the -i flag to prompt confirmation when we copy the file. Usually, a destination file is overwritten when using the CP command. This happens in that condition when the file is present at the time of copying. The command will prompt using the -i flag for overwriting the file.

We can pass the -l flag while creating a hard link instead of copying with the help of the cp command. A new file is created by not copying the file, which is a hard link to the data on the disk. This is a primer on soft or symbolic and hard links.

ls
Filename.txt
Filname1.txt
cp -l Filname.txt Filname1.txt
echo 'Filename1 text' > Filename1.txt
Filname.txt
Filename text

Preserve File Attributes

The preserve option is passed to preserve the file attributes (i.e., user ownership, group, and permissions) along with the properties to be preserved, by default, a mode that will preserve timestamp and ownership.

-rw------- 1 Linux users 0 Sept 14 04:00 bar.txt
cp --preserve bar.txt foo.txt
-rw------- 1 Linux users 0 Sept 14 04:00 foo.txt
-rw------- 1 Linux users 0 Sept 14 04:00 bar.txt

Display All Files Copied

The -v option is used in the Cp command to show the files that are copied. This option prints folders and files that are copied to standard outputs.

cp -R -v Filename Filename1
'Filename' -> 'Filename1'
'Filename/Filename.txt' -> 'Filename1/Filename.txt'
'Filename/Filename1.txt' -> 'Filename1/Filename1.txt'

Conclusion

This article described how we could copy one or more files, folders, and directories using the CP command. We explained to you many ways to use the CP command for copying the files. If there is any query or questions in your mind regarding this article, then feel free to contact us.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.

Источник

Copying multiple specific files from one folder to another

I have a large folder of pictures (thousands), and I have a long list of files, by exact file name, that I need to copy to another folder. I want to know if there is a way I can select several specific files from this folder, by name, and copy them to another folder, using the terminal, without copying them individually?

Fyi, for copying specific folders use: cp -rp /copying/from/ path/to/folder , where p is for copying the folder permission.

7 Answers 7

Simply copy multiple files at once from command line

There are several ways you could achieve this. The easiest I have seen is to use the following.

cp /home/usr/dir/ /home/usr/destination/ 

The syntax uses the cp command followed by the path to the directory the desired files are located in with all the files you wish to copy wrapped in brackets and separated by commas.

Читайте также:  Linux добавление маршрута по умолчанию

Make sure to note that there are no spaces between the files. The last part of the command, /home/usr/destination/ , is the directory you wish to copy the files into.

or if the all the files have the same prefix but different endings you could do something like this:

Where file1,file2,file3 and file4 would be copied.

From how you worded the question I believe this is what you're looking for but it also sounds like you might be looking for a command to read from a list of files and copy all of them to a certain directory. If that is the case let me know and i'll edit my answer.

Dealing with duplicates with python

So I wrote a little python script that I believe should get the job done. However, I am not sure how well versed you are in python (if versed at all) so I will try explaining how to use this script the best I can and please ask as many questions about it as you need.

import os,sys,shutil ### copies a list of files from source. handles duplicates. def rename(file_name, dst, num=1): #splits file name to add number distinction (file_prefix, exstension) = os.path.splitext(file_name) renamed = "%s(%d)%s" % (file_prefix,num,exstension) #checks if renamed file exists. Renames file if it does exist. if os.path.exists(dst + renamed): return rename(file_name, dst, num + 1) else: return renamed def copy_files(src,dst,file_list): for files in file_list: src_file_path = src + files dst_file_path = dst + files if os.path.exists(dst_file_path): new_file_name = rename(files, dst) dst_file_path = dst + new_file_name print "Copying: " + dst_file_path try: shutil.copyfile(src_file_path,dst_file_path) except IOError: print src_file_path + " does not exist" raw_input("Please, press enter to continue.") def read_file(file_name): f = open(file_name) #reads each line of file (f), strips out extra whitespace and #returns list with each line of the file being an element of the list content = [x.strip() for x in f.readlines()] f.close() return content src = sys.argv[1] dst = sys.argv[2] file_with_list = sys.argv[3] copy_files(src,dst,read_file(file_with_list)) 

This script should be relatively simple to use. First off, copy the above code into the program gedit (should be pre-installed in Ubuntu) or any other text editor.

After that is complete, save the file as move.py in your home directory (it can be any directory but for ease of instruction lets just use the home directory) or add the directory the file is contained in to your PATH. Then cd to your home directory (or whatever directory you saved move.py in) from the terminal and type the following command:

python move.py /path/to/src/ /path/to/dst/ file.txt 

This should copy all of the files that are listed from the source directory to the destination directory with duplicates taking the format pic(1).jpg, pic(2).jpg and so on. file.txt should be a file that lists all the pictures you would like to copy with each entry on its own separate line.

In no way should this script effect the source directory, however just make sure to enter the correct paths to the source and destination directory and the worst that could happen is you copy the files to the wrong directory.

Notes

  • This script assumes that all of the original pictures are in the same directory. If you want it to check sub directories as well the script will need to be modified.
  • If you accidentally mistype a file name, the script will spit out the error
    "file does not exist" and prompt you to "press enter" to continue and the script will continue copying the rest of the list.
  • Don't forget the trailing / on both the path to the source
    directory and path to the destination directory. Otherwise the script will spit an error back at you.

Источник

Оцените статью
Adblock
detector