我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
当前回答
Cp有多种用法:
$ cp --help
Usage: cp [OPTION]... [-T] SOURCE DEST
or: cp [OPTION]... SOURCE... DIRECTORY
or: cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
@AndyRoss的答案适用于
cp SOURCE DEST
样式,但是如果您使用
cp SOURCE... DIRECTORY/
cp的风格。
我认为“DEST”在这种用法中没有后面的斜杠是不明确的(即目标目录还不存在),这可能是为什么cp从未为此添加选项的原因。
下面是这个函数的版本,在dest目录上强制加一个斜杠:
cp-p() {
last=${@: -1}
if [[ $# -ge 2 && "$last" == */ ]] ; then
# cp SOURCE... DEST/
mkdir -p "$last" && cp "$@"
else
echo "cp-p: (copy, creating parent dirs)"
echo "cp-p: Usage: cp-p SOURCE... DEST/"
fi
}
其他回答
虽然已经很晚了,但对新手还是有帮助的。如果你需要自动创建文件夹,rsync应该是你最好的朋友。
rsync /path/to/sourcefile /path/to/tragetdir/thatdoestexist/
mkdir -p "$d" && cp file "$d"
(cp没有这样的选项)。
从源复制到不存在的路径
mkdir –p /destination && cp –r /source/ $_
注意:该命令复制所有文件
Cp -r用于复制所有文件夹及其内容
$_ work作为最后一个命令中创建的目标
这适用于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
试一试。
可以在Perl中使用find。命令如下所示:
find file | perl -lne '$t = "/path/to/copy/file/to/is/very/deep/there/"; /^(.+)\/.+$/; `mkdir -p $t$1` unless(-d "$t$1"); `cp $_ $t$_` unless(-f "$t$_");'
如果目录$t不存在,该命令将创建该目录。然后只将文件复制到$t中,除非文件存在于$t中。