2012-01-26 57 views
4

嗨,大家好,我有一個關於unix命令行的問題。我有很多的文件這樣的:複製包含在不同父文件夾中的許多文件(同名)

/f/f1/file.txt 

/f/f2/file.txt 

/f/f3/file.txt 

and so on... 

我想與他們的父親複製所有file.txt在另一個文件夾,如:

/g/f1/file.txt 

/g/f2/file.txt 

/g/f3/file.txt 

我不能複製的所有內容folder f因爲在每個sub-folder f1, f2, ...我有許多其他文件,我不想複製。

我怎麼能用命令行來做到這一點?最終使用bash腳本?

謝謝!

回答

6

手冊cp顯示此選項 -

--parents 
       use full source file name under DIRECTORY 

所以,如果你是bash v4你可以做這樣的事情 -

[jaypal:~/Temp/f] tree 
. 
├── f1 
│   ├── file.txt # copy this file only with parent directory f1 
│   ├── file1.txt 
│   └── file2.txt 
└── f2 
    ├── file.txt # copy this file only with parent directory f2 
    ├── file1.txt 
    └── file2.txt 

2 directories, 6 files 
[jaypal:~/Temp/f] mkdir ../g 
[jaypal:~/Temp/f] shopt -s globstar 
[jaypal:~/Temp/f] for file in ./**/file.txt; do cp --parents "$file" ../g ; done 
[jaypal:~/Temp/f] tree ../g 
../g 
├── f1 
│   └── file.txt 
└── f2 
    └── file.txt 

2 directories, 2 files 
+0

非常感謝! 這個作品就像我希望的一樣! 甚至感謝其他答案! – fibon82

+0

@ fibon82:這可能對於您的特定情況最爲簡單,但考慮到rsync,因爲它非常強大,特別是對於更復雜的情況。 – Karolos

+0

行Karolos。也謝謝你的建議! – fibon82

2

焦油有時是應對文件有所幫助:看到小測試:

kent$ tree t g 
t 
|-- t1 
| |-- file 
| `-- foo ---->####this file we won't copy 
|-- t2 
| `-- file 
`-- t3 
    `-- file 
g 

3 directories, 4 files 

kent$ cd t 

kent$ find -name "file"|xargs tar -cf - | tar -xf - -C ../g 

kent$ tree ../t ../g 
../t 
|-- t1 
| |-- file 
| `-- foo 
|-- t2 
| `-- file 
`-- t3 
    `-- file 
../g 
|-- t1 
| `-- file 
|-- t2 
| `-- file 
`-- t3 
    `-- file 
+0

+1我從來沒有使用'tar'了'move'想。優秀!解釋也非常清楚;-) – olibre

1

這似乎是它會幫助你:

find /f/ -name file.txt -execdir cp -R . /g/ \; 

它位於所有名爲file.txt的文件目錄/ f /,然後使用execdir(它在包含匹配文件的目錄中執行)將包含該文件的目錄複製到目錄/ g /。

+0

就我所瞭解的命令而言,它會將文件複製到/ g /而不保留相對路徑,例如/g/f1/file.txt,並將_overwrite_現有的file.txt,即最終贏得/ g /中的一個文件,正在複製_last_。我錯過了什麼? – Karolos

+0

是的,這是正確的。我編輯帖子從'cp'到'cp -R',這在複製目錄時顯然更有意義。 –

+0

我不認爲這個問題與-R有關。我在Mac OS X上運行你的代碼(這是BSD的unix),最後以/ g /結合文件,任何給定的名字都對應着最後一個名字被複制的文件。 – Karolos

2

rsync看看。假設你在「/」,

rsync -r f/ g/ --include "*/" --include "*/file.txt" --exclude "*" 

首先包括必要讓rsync看子目錄內(和抵消最後排除)。第二個包括選擇你想要複製的文件。排除確保其他文件不在/ f中處理不是所需的模式。

注意:如果您有符號鏈接,rsync將複製鏈接而不是鏈接指向的文件,除非您指定--copy-links

例子:

$ find f g -type f 
f/f1/file.txt 
f/f1/fileNew.txt 
f/f2/file.txt 
f/f3/file.txt 
find: g: No such file or directory 
$ rsync -r f/ g/ --include "*/" --include "*/file.txt" --exclude "*" 
$ find f g -type f 
f/f1/file.txt 
f/f1/fileNew.txt 
f/f2/file.txt 
f/f3/file.txt 
g/f1/file.txt 
g/f2/file.txt 
g/f3/file.txt 
相關問題