我需要一个命令(可能是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,这也可以工作。
其他回答
仅适用于macOS
rsync -R <source file path> destination_folder
对于macOS -父母cp选项不工作
我尊重上面的答案,我更喜欢使用rsync如下所示:
$ rsync -a directory_name /path_where_to_inject_your_directory/
例子:
$ rsync -a test /usr/local/lib/
Shell函数,做你想要的,称它为“埋葬”副本,因为它为文件挖了一个洞:
bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }
可以在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中。
mkdir -p "$d" && cp file "$d"
(cp没有这样的选项)。