我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
当前回答
如果以下两个条件都成立:
您使用的是GNU版本的cp(而不是Mac版本),并且 您正在从一些现有的目录结构进行复制,您只需要重新创建它
然后你可以用cp的——parents标志来做。从信息页面(可以在http://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#cp-invocation或info cp或man cp查看):
——父母 通过追加到目标文件来形成每个目标文件的名称 目录中包含斜杠和源文件的指定名称。的 给' cp'的最后一个参数必须是现有的 目录中。例如,命令: Cp——parents a/b/c existing_dir 复制文件' a/b/c'到' existing_dir/a/b/c',创建any 缺少中间目录。
例子:
/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
其他回答
我强烈建议你也这么做。 只是工作。
同样,my/location/poo .txt this/doesn /exist/yet/poo .txt
Shell函数,做你想要的,称它为“埋葬”副本,因为它为文件挖了一个洞:
bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }
这适用于MacOS上的GNU /bin/bash版本3.2(在Catalina和Big Sur上都进行了测试)
cp -Rv <existing-source-folder>/ <non-existing-2becreated-destination-folder>
“v”选项表示冗长。
我认为"-R"选项是"递归"
人类对-R的完整描述是:
If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. If the source_file ends in a /, the contents of the directory are copied rather than the directory itself. This option also causes symbolic links to be copied, rather than indirected through, and for cp to create special files rather than copying them as normal files. Created directories have the same mode as the corresponding source directory, unmodified by the process' umask. In -R mode, cp will continue copying even if errors are detected. Note that cp copies hard-linked files as separate files. If you need to preserve hard links, consider using tar(1), cpio(1), or pax(1) instead.
在下面的例子中,我在existingfolder的末尾使用了一个“/”,这样它就会将existingfolder的所有内容(而不是文件夹本身)复制到newfolder中:
cp -Rv existingfolder/ newfolder
试一试。
简短的回答
复制myfile.txt到/foo/bar/myfile.txt,使用:
mkdir -p /foo/bar && cp myfile.txt $_
这是如何工作的呢?
这里有几个组件,所以我将一步一步地介绍所有语法。
POSIX标准中指定的mkdir实用程序创建目录。根据文档,-p参数将导致mkdir
创建任何缺少的中间路径名组件
这意味着当调用mkdir -p /foo/bar时,如果/foo不存在,mkdir将创建/foo和/foo/bar。(如果没有-p,它将抛出一个错误。
&&列表操作符,如POSIX标准(或Bash手册,如果你喜欢)中所述,其效果是只有在mkdir -p /foo/bar成功执行时才执行cp myfile.txt $_。这意味着如果mkdir失败,cp命令将不会尝试执行,原因有很多。
最后,我们传递给cp的第二个参数$_是一个“特殊参数”,可以方便地避免重复长参数(如文件路径),而不必将它们存储在变量中。根据Bash手册,它:
展开到上一个命令的最后一个参数
在本例中,这是我们传递给mkdir的/foo/bar。因此cp命令展开为cp myfile.txt /foo/bar,将myfile.txt复制到新创建的/foo/bar目录中。
注意$_不是POSIX标准的一部分,所以理论上Unix变体可能有一个不支持这个构造的shell。然而,我不知道任何现代shell不支持$_;当然Bash, Dash和zsh都喜欢。
最后注意:我在回答开头给出的命令假设目录名中没有空格。如果你正在处理带有空格的名称,你需要引用它们,这样不同的单词就不会被视为mkdir或cp的不同参数。所以你的命令实际上是这样的:
mkdir -p "/my directory/name with/spaces" && cp "my filename with spaces.txt" "$_"
mkdir -p "$d" && cp file "$d"
(cp没有这样的选项)。