如何让cp命令创build任何必要的文件夹来将文件复制到目的地

当使用cp将文件复制到可能存在或不存在的文件夹时,如何获取cp以在必要时创build文件夹? 这是我所尝试的:

 [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. 您正在使用cp的GNU版本(而不是,例如,Mac版本)和
  2. 你正在复制一些现有的目录结构,你只需要重新创build它

那么你可以用cp--parents标志来做到这一点。 从信息页面(可在http://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#cp-invocation或;info cpman cp查看):

 --parents Form the name of each destination file by appending to the target directory a slash and the specified name of the source file. The last argument given to `cp' must be the name of an existing directory. For example, the command: cp --parents a/b/c existing_dir copies the file `a/b/c' to `existing_dir/a/b/c', creating any missing intermediate directories. 

例:

 /tmp $ mkdir foo /tmp $ mkdir foo/foo /tmp $ touch foo/foo/foo.txt /tmp $ mkdir bar /tmp $ cp --parents foo/foo/foo.txt bar /tmp $ ls bar/foo/foo foo.txt 

为了扩大基督徒的答案,唯一可靠的方法是将mkdircp结合起来:

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

另外,当你只需要在现有的层次结构中创build一个目录时, rsync可以在一个操作中完成。 事实上,我非常喜欢rsync作为更多function的cp替代品,

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

我不知道你可以用cp来做到这一点。

你可以用mkdir来做

 mkdir -p /var/path/to/your/dir 

编辑请参阅lhunath的关于合并cp的答案 。

对于那些在Mac OSX上,也许最简单的方法来解决这个问题是使用同上 (只在MAC,AFAIK,虽然)。 它将创build目标中缺less的目录结构。

例如,我做了这个

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

在运行命令之前~/work没有包含二进制文件目录。

我认为rsync应该类似的工作,但似乎只适用于一级缺less的目录。 那是,

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

因为〜/ work / binaries / macosx已经存在,而不是〜/ work / binaries / macosx / 6.3.2 /

  mkdir -p `dirname /nosuchdirectory/hi.txt` && cp -r urls-resume /nosuchdirectory/hi.txt 

也可以使用命令find

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

没有这样的select。 你可以做的是在复制文件之前运行mkdir -p

我做了一个非常酷的脚本,你可以用它来复制不存在的位置的文件

 #!/bin/bash if [ ! -d "$2" ]; then mkdir -p "$2" fi cp -R "$1" "$2" 

现在保存它,给它权限并使用它来运行

 ./cp-improved SOURCE DEST 

我把-R选项,但这只是一个草案,我知道它可以,你会改善它在很多方面。 希望它可以帮助你

rsync工作!

 #file: rsync -aqz _vimrc ~/.vimrc #directory: rsync -aqz _vim/ ~/.vim 
 cp -Rvn /source/path/* /destination/path/ cp: /destination/path/any.zip: No such file or directory 

它将在目标中创build没有现有的path,如果path中有一个源文件。 这不会创build空目录。

刚才我见过xxxxxxxx:没有这样的文件或目录,因为我用完了空闲空间。 没有错误信息。

同上:

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

一旦释放空间cp -Rvn /source/path/* /destination/path/按预期工作

令人惊讶的是,我没有看到在这个线程中正确的答案,只是使用:

 cp -r /foo/bar/baz /tmp 

像往常一样,一个简单的RTFMbuild议就足够了,以上将复制baz文件在/ tmp和子目录foo / bar(如果它们不存在将被创build)

 cp --help -R, -r, --recursive copy directories recursively