我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
当前回答
只是恢复和给出一个完整的工作解决方案,在一行。 如果您想要重命名文件,请注意,您应该包括一种方法来提供到mkdir的干净dir路径。$fdst可以是file或dir。 下一段代码在任何情况下都可以工作。
fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p $(dirname ${fdst}) && cp -p ${fsrc} ${fdst}
或者特定于bash
fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p ${fdst%/*} && cp -p ${fsrc} ${fdst}
其他回答
这适用于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
试一试。
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 file /path/to/copy/file/to/is/very/deep/there
如果您有正确的rsync类型,这可能会起作用。
我也有同样的问题。我的方法是把这些文件压缩成一个存档,就像这样:
tar cf你档案。tar file1 /path/to/file2路径/to/even/deeper/file3
Tar自动将文件存储在归档文件中的适当结构中。如果你跑了
Tar xf your_archive.tar
文件被提取到所需的目录结构中。
只需在你的.bashrc中添加以下代码,如果需要可以调整。适用于Ubuntu。
mkcp() {
test -d "$2" || mkdir -p "$2"
cp -r "$1" "$2"
}
如 如果您想将“test”文件复制到目标目录“d” 使用,
mkcp test a/b/c/d
MKCP将首先检查目标目录是否存在,如果不存在则创建并复制源文件/目录。