LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   cp command help (https://www.linuxquestions.org/questions/linux-newbie-8/cp-command-help-868523/)

mpranav007 03-14-2011 12:45 PM

cp command help
 
I have around 500 files in a folder. But I don't want to copy all of them. The name of the files that I want to copy is in a txt file.

The question is how to use the names from the txt file as arguments for the cp command.

Nylex 03-14-2011 12:52 PM

You need to read the lines from the file into a variable and then use that variable as an argument to the cp command. For example, consider the file "numbers":

1
2
3
4

A simple shell script to read the values from this file and print the numbers is as follows:

Code:

#!/bin/bash

exec < numbers # Replace "stdin" (i.e. the command line) with the file "numbers".

while read line # Read each line from the file
do
  echo $line # Print the number that was read
done

For more information about shell scipting (in Bash), see the Advanced Bash-Scripting Guide. In particular, chapters 11 and 20 are relevant.

siranjeevi 03-14-2011 06:17 PM

Hi,

I hope you are trying to copy the files and not the lines in a file, if so, here is your option.


Quote:

cp /path/to/souce/folder/*.txt /path/to/destination/folder/
The above command will copy all the files ending with name .txt.

z1p 03-14-2011 07:02 PM

In addition of writing a shell script as nylex suggested, you can easily do it from the command line. For example in the bash shell the following would copy all the files listed in my_file_list.txt to /my/dest_dir

Code:

for i in `cat my_file_list.txt`; do cp $i /my/dest_dir; done

WilliamHerry 03-14-2011 07:17 PM

Quote:

Originally Posted by z1p (Post 4290906)
In addition of writing a shell script as nylex suggested, you can easily do it from the command line. For example in the bash shell the following would copy all the files listed in my_file_list.txt to /my/dest_dir

Code:

for i in `cat my_file_list.txt`; do cp $i /my/dest_dir; done

If i see this early, i would get that job!

grail 03-15-2011 01:48 AM

Depending on whether or not you are copying all the file to the same location, you could simply do:
Code:

cp $(< file) location/
This assumes that the file either contains the path to each file or that you are within the directory of all said files.
And of course that the destination 'location' exists.

siranjeevi 03-15-2011 05:32 AM

Quote:

Originally Posted by siranjeevi (Post 4290868)
Hi,

I hope you are trying to copy the files and not the lines in a file, if so, here is your option.




The above command will copy all the files ending with name .txt.

Hi,

Sorry for that mis leading message, I took your question i a wrong sense. You can go with Nylex and z1p's option.


All times are GMT -5. The time now is 05:11 PM.