Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a file including it's relative path

I need to copy a large number of files to a backup folder but I want to maintain their relative paths. I only need specific files; i.e.

C:\scripts\folder\File.ext1
C:\scripts\folder2\file2.ext2
C:\scripts\file3.ext1

But I only need to copy the ext1 files like so:

C:\backup\folder\File.ext1.bak
C:\backup\file3.ext1.bak

The source paths are of multiple depths. This is what I have to copy the files:

$files = gci -path C:\scripts\ -recurse -include *.ext1 
$files | % { Copy-Item $_ "$($_).bak"; move-item $_ -destination C:\backup\ }

This just dumps all the files into C:\backup\ and does not appear to get any of the paths. Not sure how that part would be done.

like image 372
MrGrant Avatar asked Feb 08 '11 17:02

MrGrant


People also ask

How do I copy a relative path in Linux?

To copy a file to another directory, specify the absolute or the relative path to the destination directory. When only the directory name is specified as a destination, the copied file has the same name as the original file. If you want to copy the file under a different name, you need to specify the desired file name.

How do I copy a file to another path?

Right-click and pick Copy, or press Ctrl + C . Navigate to another folder, where you want to put the copy of the file. Click the menu button and pick Paste to finish copying the file, or press Ctrl + V . There will now be a copy of the file in the original folder and the other folder.


1 Answers

Something like this could work:

gci -path C:\scripts\ -recurse -include *.ext1 | 
  % { Copy-Item $_.FullName "$($_.FullName).bak"
      move-item $_.FullName -destination ($_.FullName -replace 'C:\\scripts\\','C:\backup\') }

It is not clever, but it's quick & dirty and works without a lot of effort.

like image 57
stej Avatar answered Sep 22 '22 05:09

stej