我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
当前回答
许多其他解决方案都不能用于需要转义的文件或文件夹。下面是一个解决方案,它适用于文件和文件夹,并转义空格和其他特殊字符。测试在一个繁忙箱灰壳,没有访问一些花哨的选项。
export file="annoying folder/bar.txt"
export new_parent="/tmp/"
# Creates /tmp/annoying folder/
mkdir -p "$(dirname "$new_folder/$file")"
# Copies file to /tmp/annoying folder/bar.txt
cp -r "$file" "$new_folder/$file"
如果您需要整个文件夹的递归副本而省略了bar.txt,这也可以工作。
其他回答
比如说你在做
cp file1.txt A/B/C/D/文件txt
其中A/B/C/D是还不存在的目录
一个可能的解决方案如下
DIR=$(dirname A/B/C/D/file.txt)
# DIR= "A/B/C/D"
mkdir -p $DIR
cp file1.txt A/B/C/D/file.txt
希望有帮助!
install -D file -m 644 -t /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
可以在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中。
这适用于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
试一试。