Linux:复制并创建目标目录(如果不存在)
我想要一个命令(或者可能是 cp 的选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(29)
cp
有多种用法:@AndyRoss 的答案适用于
则会出现错误
cp
的样式,但如果您使用cp
的样式,。我认为“DEST”在这种用法中没有尾部斜杠是不明确的(即目标目录尚不存在),这也许就是为什么
cp
从未为此添加选项的原因。所以这是我的这个函数的版本,它在目标目录上强制使用尾部斜杠:
cp
has multiple usages:@AndyRoss's answer works for the
style of
cp
, but does the wrong thing if you use thestyle of
cp
.I think that "DEST" is ambiguous without a trailing slash in this usage (i.e. where the target directory doesn't yet exist), which is perhaps why
cp
has never added an option for this.So here's my version of this function which enforces a trailing slash on the dest dir:
刚刚有同样的问题。我的方法是将文件压缩到存档中,如下所示:
tar cf your_archive.tar file1 /path/to/file2 path/to/even/deeper/file3
tar 自动将文件存储在适当的位置档案内的结构。如果运行
tar xf your_archive.tar
,文件将被提取到所需的目录结构中。
Just had the same issue. My approach was to just tar the files into an archive like so:
tar cf your_archive.tar file1 /path/to/file2 path/to/even/deeper/file3
tar automatically stores the files in the appropriate structure within the archive. If you run
tar xf your_archive.tar
the files are extracted into the desired directory structure.
从源复制到不存在的路径
注意:此命令复制所有文件
cp –r
用于复制所有文件夹及其内容$_
作为最后创建的目标命令Copy from source to an non existing path
NOTE: this command copies all the files
cp –r
for copying all folders and its content$_
work as destination which is created in last commandOneliner 创建一个可以用作子命令的小脚本,例如在
find
中:set +H; echo -e "#!/bin/sh\nmkdir -p \$(目录名 \"\$2\"); cp \"\$1\" \"$2\"\;" > 〜/本地/bin/cpmkdir; chmod +x ~/local/bin/cpmkdir
然后您可以像这样使用它:
find -name files_you_re_lookin_for.* -exec cpmkdir {} ../extracted_copy/{} \;
Oneliner to create a small script that can be used as subcommand, in
find
for instance:set +H; echo -e "#!/bin/sh\nmkdir -p \$(dirname \"\$2\"); cp \"\$1\" \"$2\"\;" > ~/local/bin/cpmkdir; chmod +x ~/local/bin/cpmkdir
You can then use it like:
find -name files_you_re_lookin_for.* -exec cpmkdir {} ../extracted_copy/{} \;
如果您有正确类型的
rsync
,这可能会起作用。This might work, if you have the right kind of
rsync
.您可以将
find
与Perl
结合使用。命令将如下所示:如果目录
$t
不存在,则该命令将创建该目录。并且仅将file
复制到$t
中,除非file
存在于$t
中。You can use
find
withPerl
. Command will be like this:This command will create directory
$t
if it doesn't exist. And than copyfile
into$t
only unlessfile
exists inside$t
.这适用于 MacOS 上的 GNU /bin/bash 版本 3.2(在 Catalina 和 Big Sur 上测试),
“v”选项表示详细。
我认为“-R”选项是“递归”。
man 对 -R 的完整描述是:
在下面的示例中,我在现有文件夹末尾使用“/”,以便将现有文件夹的所有内容(而不是文件夹本身)复制到新文件夹中:
尝试一下。
This works on GNU /bin/bash version 3.2 on MacOS (tested on both Catalina and Big Sur)
the "v" option is for verbose.
And I think of the "-R" option as "Recursive".
man's full description of -R is:
In the example below, I'm using a "/" at the end of existingfolder so that it copies all the contents of existingfolder (and not the folder itself) into newfolder:
Try it.
许多其他解决方案不适用于需要转义的文件或文件夹。这是一个适用于文件和文件夹的解决方案,并转义空格和其他特殊字符。在 busybox ash shell 中进行了测试,该 shell 无法访问某些更高级的选项。
如果您需要整个文件夹的递归副本,则省略
bar.txt
也应该有效。Many of the other solutions don't work on files or folders which need escaping. Here is a solution which works for files and folders, and escapes spaces and other special characters. Tested in a busybox ash shell which doesn't have access to some of the fancier options.
This should also work if you omit
bar.txt
if you need the recursive copy of a whole folder.假设你正在做类似的事情
其中 A/B/C/D 是尚不存在的目录
可能的解决方案如下
希望有所帮助!
Let's say you are doing something like
where A/B/C/D are directories which do not exist yet
A possible solution is as follows
hope that helps!
仅适用于 macOS
对于macOS --cp 的parents 选项不起作用
Only for macOS
For macOS --parents option of cp doesn't work
(如果我的答案没有在这里被阻止...)这对 rsync 没有帮助吗:
如果不存在,则创建 destdir。
(If my answer doesn't get blocked here...) couldn't this help in rsync:
The destdir is created if non-existent.
将文件从
./assets/
复制到当前日期的其他目录更多信息:
将 x 的内容复制到 y 目录 x/a.txt y/a.txt :
仅复制 a.txt 和 b.txt从 x 到 y 目录:
本地到远程:
远程到本地:
从文件中忽略:
Copy files from
./assets/
to other dir with current dateMore Information:
Copy content of x to y directory x/a.txt y/a.txt :
Copy a.txt and b.txt only from x to y dir :
Local to remote :
Remote to local :
Ignore from a file :
简单
应该可以解决问题。
Simple
should do the trick.
(
cp
没有这样的选项)。(there's no such option for
cp
).如果以下两个条件都为真:
那么您可以使用
cp
的--parents
标志来完成此操作。从信息页面(可在 http://www.gnu.org 查看/software/coreutils/manual/html_node/cp-in Vocation.html#cp-inspiration 或使用info cp
或man cp
):例子:
If both of the following are true:
cp
(and not, for instance, the Mac version), andthen you can do this with the
--parents
flag ofcp
. From the info page (viewable at http://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#cp-invocation or withinfo cp
orman cp
):Example:
简短回答
要将
myfile.txt
复制到/foo/bar/myfile.txt
,请使用:这是如何工作的?
其中有几个组件,因此我将逐步介绍所有语法。
mkdir 实用程序,按照 POSIX 标准中的规定,创建目录。根据文档,
-p
参数将导致 mkdir这意味着在调用
mkdir -p /foo/bar
时,mkdir 将创建/foo
和/foo/bar
如果/foo
尚不存在。 (如果没有-p
,它会抛出错误。&&
列表运算符,如 POSIX 标准(或Bash 手册(如果您愿意),其效果是仅当mkdir -p /foo/bar
执行时才执行cp myfile.txt $_
这意味着如果 mkdir 失败,则cp
命令不会尝试执行。 functions/mkdir.html#tag_03_371_05">它可能失败的众多原因之一。最后,我们作为第二个参数传递给
cp
的$_
是一个“特殊参数”,可以方便地避免重复长参数(如文件路径),而不必将它们存储在变量中。 html_node/Special-Parameters.html">Bash 手册,它:在本例中,这就是我们传递给
mkdir
的/foo/bar
。因此,cp
命令扩展为cp myfile.txt /foo/bar
,它将myfile.txt
复制到新创建的/foo 中/bar
目录。请注意,
$_
不是的一部分POSIX 标准,因此理论上 Unix 变体可能有不支持此构造的 shell。但是,我不知道有哪个现代 shell 不支持$_
;当然,Bash、Dash 和 zsh 都可以。最后一点:我在本答案开头给出的命令假设您的目录名称中没有空格。如果您正在处理带有空格的名称,则需要引用它们,以便不同的单词不被视为
mkdir
或cp
的不同参数。所以你的命令实际上看起来像:Short Answer
To copy
myfile.txt
to/foo/bar/myfile.txt
, use:How does this work?
There's a few components to this, so I'll cover all the syntax step by step.
The mkdir utility, as specified in the POSIX standard, makes directories. The
-p
argument, per the docs, will cause mkdir tomeaning that when calling
mkdir -p /foo/bar
, mkdir will create/foo
and/foo/bar
if/foo
doesn't already exist. (Without-p
, it will instead throw an error.The
&&
list operator, as documented in the POSIX standard (or the Bash manual if you prefer), has the effect thatcp myfile.txt $_
only gets executed ifmkdir -p /foo/bar
executes successfully. This means thecp
command won't try to execute ifmkdir
fails for one of the many reasons it might fail.Finally, the
$_
we pass as the second argument tocp
is a "special parameter" which can be handy for avoiding repeating long arguments (like file paths) without having to store them in a variable. Per the Bash manual, it:In this case, that's the
/foo/bar
we passed tomkdir
. So thecp
command expands tocp myfile.txt /foo/bar
, which copiesmyfile.txt
into the newly created/foo/bar
directory.Note that
$_
is not part of the POSIX standard, so theoretically a Unix variant might have a shell that doesn't support this construct. However, I don't know of any modern shells that don't support$_
; certainly Bash, Dash, and zsh all do.A final note: the command I've given at the start of this answer assumes that your directory names don't have spaces in. If you're dealing with names with spaces, you'll need to quote them so that the different words aren't treated as different arguments to
mkdir
orcp
. So your command would actually look like:这是一个老问题,但也许我可以提出一个替代解决方案。
您可以使用
install
程序来复制文件并“即时”创建目标路径。不过,有一些方面需要考虑:
您可以通过添加
-m
选项来轻松修改 #2 以设置目标文件的权限(例如:-m 664
将使用权限rw-rw-r--
创建目标文件,就像使用touch
创建新文件一样)。这是无耻的链接到我受到启发的答案 =)
Such an old question, but maybe I can propose an alternative solution.
You can use the
install
programme to copy your file and create the destination path "on the fly".There are some aspects to take in consideration, though:
You can easily amend the #2 by adding the
-m
option to set permissions on the destination file (example:-m 664
will create the destination file with permissionsrw-rw-r--
, just like creating a new file withtouch
).And here it is the shameless link to the answer I was inspired by =)
Shell 函数可以完成您想要的操作,将其称为“埋葬”副本,因为它为文件挖了一个洞:
Shell function that does what you want, calling it a "bury" copy because it digs a hole for the file to live in:
这是一种方法:
dirname
将为您提供目标目录或文件的父级。 mkdir -p `dirname ...` 将创建该目录,确保当您调用 cp -r 时正确的基目录已就位。与 --parents 相比,它的优点是它适用于目标路径中最后一个元素是文件名的情况。
并且它可以在 OS X 上运行。
Here's one way to do it:
dirname
will give you the parent of the destination directory or file. mkdir -p `dirname ...` will then create that directory ensuring that when you call cp -r the correct base directory is in place.The advantage of this over --parents is that it works for the case where the last element in the destination path is a filename.
And it'll work on OS X.
虽然已经很晚了,但它可能会对新手有所帮助。如果您需要自动创建文件夹,
rsync
应该是您最好的朋友。This is very late but it may help a rookie somewhere. If you need to AUTO create folders
rsync
should be your best friend.出于对上述答案的尊重,我更喜欢使用 rsync,如下所示:
示例:
with all my respect for answers above, I prefer to use rsync as follow:
example:
安装-D文件-m 644 -t /path/to/copy/file/to/is/very/deep/there
install -D file -m 644 -t /path/to/copy/file/to/is/very/deep/there
这对我有用
This does it for me
正如上面 help_asap 和 Spongeman 所建议的,您可以使用“install”命令将文件复制到现有目录,或者创建新的目标目录(如果它们尚不存在)。
选项1
install -D filename some/deep/directory/filename
将文件复制到新的或现有的目录并赋予文件名默认 755 权限
选项 2
安装 -D 文件名 -m640 some/deep/directory/filename
按照选项 1,但给予文件名 640 权限。
选项3
安装 -D 文件名 -m640 -t some/deep/directory/
按照选项 2,但将文件名定位到目标目录中,因此不需要在源和目标中都写入文件名。
选项4
安装 -D filena* -m640 -t some/deep/directory/
与选项 3 相同,但对多个文件使用通配符。
它在 Ubuntu 中运行良好,并将两个步骤(目录创建然后文件复制)合并为一个步骤。
As suggested above by help_asap and spongeman you can use the 'install' command to copy files to existing directories or create create new destination directories if they don't already exist.
Option 1
install -D filename some/deep/directory/filename
copies file to a new or existing directory and gives filename default 755 permissions
Option 2
install -D filename -m640 some/deep/directory/filename
as per Option 1 but gives filename 640 permissions.
Option 3
install -D filename -m640 -t some/deep/directory/
as per Option 2 but targets filename into target directory so filename does not need to be written in both source and target.
Option 4
install -D filena* -m640 -t some/deep/directory/
as per Option 3 but uses a wildcard for multiple files.
It works nicely in Ubuntu and combines two steps (directory creation then file copy) into one single step.
只需在 .bashrc 中添加以下内容,并根据需要进行调整。在 Ubuntu 中工作。
例如
如果要将“test”文件复制到目标目录“d”
使用时,
mkcp会首先检查目标目录是否存在,如果不存在则创建并复制源文件/目录。
Simply add the following in your .bashrc, tweak if you need. Works in Ubuntu.
E.g
If you want to copy 'test' file to destination directory 'd'
Use,
mkcp will first check if destination directory exists or not, if not then make it and copy source file/directory.
只是为了恢复并在一行中提供完整的工作解决方案。
如果您想重命名文件,请小心,您应该提供一种为 mkdir 提供干净的 dir 路径的方法。 $fdst 可以是文件或目录。
接下来的代码在任何情况下都应该有效。
或 bash 特定的
Just to resume and give a complete working solution, in one line.
Be careful if you want to rename your file, you should include a way to provide a clean dir path to mkdir. $fdst can be file or dir.
Next code should work in any case.
or bash specific
无需创建脚本并使用简单的命令...
Simply without creating script and with simple command ...
我强烈建议
同上
。就可以了。
同上 my/location/poop.txt this/doesnt/exist/yet/poop.txt
i strongly suggest
ditto
.just works.
ditto my/location/poop.txt this/doesnt/exist/yet/poop.txt
我为 cp 编写了一个支持脚本,称为 CP(注意大写字母),其目的正是为了实现此目的。脚本将检查您输入的路径中是否有错误(最后一个目标除外),如果一切正常,它将在开始复制之前执行 mkdir -p 步骤来创建目标路径。此时,常规 cp 实用程序将接管,并且与 CP 一起使用的任何开关(例如 -r、-p、-rpL 都会直接通过管道传输到 cp)。在使用我的脚本之前,您需要了解一些事情。
CP 无法从现有路径中获取线索,因此它必须有一些非常坚定的行为模式。 CP 假定您要复制的项目被放置在目标路径中,而不是目标本身(也称为源文件/文件夹的重命名副本)。含义:
可以使用“--rename”开关更改此默认 CP 行为。在本例中,假设
一些结束语:与 cp 一样,CP 可以一次复制多个项目,并假定列出的最后一个路径是目标。只要使用引号,它也可以处理带有空格的路径。
CP 将检查您输入的路径并确保它们存在,然后再进行复制。在严格模式下(可通过 --strict 开关使用),要复制的所有文件/文件夹必须存在,否则不进行复制。在宽松模式 (--relaxed) 下,如果您列出的至少一项存在,则复制将继续。宽松模式是默认模式,您可以通过开关临时更改模式,也可以通过在脚本开头设置变量 easy_going 来永久更改模式。
安装方法如下:
在非 root 终端中,执行以下操作:
在 gedit 中,粘贴 CP 实用程序并保存:
I wrote a support script for cp, called CP (note capital letters) that's intended to do exactly this. Script will check for errors in the path you've put in (except the last one which is the destination) and if all is well, it will do an mkdir -p step to create the destination path before starting the copy. At this point the regular cp utility takes over and any switches you use with CP (like -r, -p, -rpL gets piped directly to cp). Before you use my script, there are a few things you need to understand.
CP doesn't have the luxury of taking cues from existing paths, so it has to have some very firm behavior patterns. CP assumes that the item you're copying is being dropped in the destination path and is not the destination itself (aka, a renamed copy of the source file/folder). Meaning:
This default CP behavior can be changed with the "--rename" switch. In this case, it's assumed that
A few closing notes: Like with cp, CP can copy multiple items at a time with the last path being listed assumed to be the destination. It can also handle paths with spaces as long as you use quotation marks.
CP will check the paths you put in and make sure they exist before doing the copy. In strict mode (available through --strict switch), all files/folders being copied must exist or no copy takes place. In relaxed mode (--relaxed), copy will continue if at least one of the items you listed exists. Relaxed mode is the default, you can change the mode temporarily via the switches or permanently by setting the variable easy_going at the beginning of the script.
Here's how to install it:
In a non-root terminal, do:
In gedit, paste CP utility and save: