如何讓cp命令創建任何必要的文件夾以將文件複製到目標[重複]

本文翻譯自:How to have the cp command create any necessary folders for copying a file to a destination [duplicate]

This question already has an answer here: 這個問題在這裏已有答案:

When copying a file using cp to a folder that may or may not exist, how do I get cp to create the folder if necessary? 使用cp將文件複製到可能存在或不存在的文件夾時,如何在必要時獲取cp來創建文件夾? Here is what I have tried: 這是我嘗試過的:

[root@file nutch-0.9]# cp -f urls-resume /nosuchdirectory/hi.txt
cp: cannot create regular file `/nosuchdirectory/hi.txt': No such file or directory

#1樓

參考:https://stackoom.com/question/3yba/如何讓cp命令創建任何必要的文件夾以將文件複製到目標-重複


#2樓

也可以使用命令find

find ./ -depth -print | cpio -pvd newdirpathname

#3樓

For those that are on Mac OSX, perhaps the easiest way to work around this is to use ditto (only on the mac, AFAIK, though). 對於那些使用Mac OSX的人來說,解決這個問題的最簡單方法可能就是使用ditto (僅限於mac,AFAIK)。 It will create the directory structure that is missing in the destination. 它將創建目標中缺少的目錄結構。

For instance, I did this 例如,我這樣做了

ditto 6.3.2/6.3.2/macosx/bin/mybinary ~/work/binaries/macosx/6.3.2/

where ~/work did not contain the binaries directory before I ran the command. 在運行命令之前, ~/work沒有包含二進制目錄。

I thought rsync should work similarly, but it seems it only works for one level of missing directories. 我認爲rsync應該工作類似,但它似乎只適用於一個級別的丟失目錄。 That is, 那是,

rsync 6.3.3/6.3.3/macosx/bin/mybinary ~/work/binaries/macosx/6.3.3/

worked, because ~/work/binaries/macosx existed but not ~/work/binaries/macosx/6.3.2/ 工作,因爲〜/ work / binaries / macosx存在但不是〜/ work / binaries / macosx / 6.3.2 /


#4樓

To expand upon Christian's answer, the only reliable way to do this would be to combine mkdir and cp : 爲了擴展Christian的答案,唯一可行的方法是將mkdircp結合起來:

mkdir -p /foo/bar && cp myfile "$_"

As an aside, when you only need to create a single directory in an existing hierarchy, rsync can do it in one operation. 另外,當您只需要在現有層次結構中創建單個目錄時, rsync可以在一個操作中執行此操作。 I'm quite a fan of rsync as a much more versatile cp replacement, in fact: 我非常喜歡rsync作爲一個更通用的cp替代品,事實上:

rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't.  bar is created.

#5樓

cp -Rvn /source/path/* /destination/path/
cp: /destination/path/any.zip: No such file or directory

It will create no existing paths in destination, if path have a source file inside. 如果路徑中包含源文件,它將在目標中不創建現有路徑。 This dont create empty directories. 這不會創建空目錄。

A moment ago i've seen xxxxxxxx: No such file or directory, because i run out of free space. 剛纔我見過xxxxxxxx:沒有這樣的文件或目錄,因爲我用完了空閒空間。 without error message. 沒有錯誤消息。

with ditto: 與同上:

ditto -V /source/path/* /destination/path
ditto: /destination/path/any.zip: No space left on device

once freed space cp -Rvn /source/path/* /destination/path/ works as expected 一旦釋放空間cp -Rvn /source/path/* /destination/path/按預期工作


#6樓

rsync is work! rsync是有效的!

#file:
rsync -aqz _vimrc ~/.vimrc

#directory:
rsync -aqz _vim/ ~/.vim
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章