copy files and create the directories if it doesn’t exist
June 3rd, 2011 mysurface Posted in dirname | Hits: 90931 | 11 Comments »
It always have a need for this simple operation.
I wanna copy certain files to a destination, but I wanna preserved the sub directories structure, any cp option to set? For examples, I wanna copy my_project/cpp/hello.cc to your_project folder, but I want it to appear as your_project/cpp/hello.cc automatically. Especially I wanna do it in a batch of file.
By just using cp command, until today, I do not see such option for it.
You need additional commands, dirname and mkdir.
You may read a list of file from a file like this
filelist="myfilelist.txt"
while read line
do
# do your copy over here
done < $filelist
First you extract the directory name of the file you wanna copy, and then create the directory, lastly copy over the file.
filelist="myfilelist.txt" # assume your filename with relative path.
target="your_project"
while read line
do
target_dir=`dirname $line`
mkdir -p $target_dir
cp $line $target$target_dir
done < $filelist
P.S. The snapshot of the code above might not work for all case, it depends on your filename in your file list, but gives you and idea on how to copy files and create directories if it doesn’t exist.







June 3rd, 2011 at 5:10 pm
How about doing a cp -R my_project/* your_project/
Should keep your directory structure and files.
cheers, j.
June 3rd, 2011 at 5:12 pm
Johannes, that is for all files in my_project to your_project, if you have specific set of files to copy, you can’t use * :D
June 3rd, 2011 at 6:23 pm
Guess i need another cup of coffee. heh. :)
June 3rd, 2011 at 8:38 pm
cd my_project
cp –parent cpp/hello.cc full/path/to/your_project
July 9th, 2011 at 10:49 am
Make the misstake will kill yourself.
July 19th, 2011 at 4:53 am
From the base directory you want to copy
{filename} | cpio -pd {destination_directory}
I use it a lot from svn status. Simply awesome.
September 30th, 2011 at 3:50 pm
Hi,,
I have try this but i think a lot of mistakes in it please keep checking then update it.
Thanks
October 12th, 2011 at 11:41 am
How about using tar?
cd my_project
tar cf – –files-from filelist.txt | ( cd ../your_project && tar xfp -)
November 2nd, 2011 at 6:45 am
mv is to move a director?
September 10th, 2012 at 3:18 pm
It can be done in many ways. The script which is used earlier is good.
February 1st, 2013 at 4:52 pm
cd is to move into directory