如何将文件复制到新位置,同时创建目录
我想将文件cp
到另一个目录,但该目录尚不存在。
所以我会这样做:
mkdir /new_place cp the_file /new_place
我可以一个人这样做吗?
我想像cp the_file -m /new_place
如果“m”代表“make dir’不存在”
这是一个使用scp,rsync或其他复制实用程序的机会吗?
使用--parents
您可以重新创建从源到目标的目录。 例如:
cp --parents ~/Downloads/test.txt ~/Desktop/
将创建子目录~/Desktop/home/desgua/Downloads
然后将test.txt
复制到其中; 和
cp --parents Downloads/test.txt ~/Desktop/
将创建~/Desktop/Downloads
。
您可以使用以下命令执行此操作
# rsync --recursive the_file /path/to/your/dir/that/doesn't/exists/
注意:在路径末尾使用“/”:
-
在源的末尾使用“/”时,rsync将复制最后一个文件夹的内容。 如果不在源的末尾使用“/”,rsync将复制最后一个文件夹和文件夹的内容。
-
在目标末尾使用“/”时,rsync会将数据粘贴到最后一个文件夹中。 如果在目标末尾不使用“/”,rsync将创建一个包含最后一个目标文件夹名称的文件夹,并将数据粘贴到该文件夹中。
desgua的答案是正确而简单的方法,但是如果你需要一个可靠的方法呢? POSIX定义了没有--parent
标志的cp
,所以它不适用于所有系统。
一种选择是在Python中编写它,如果它安装在系统上:
#!/usr/bin/env python3 from os import makedirs from os.path import exists,basename from shutil import copyfile from sys import argv if len(argv) < 3: print('Not enough args',file=stderr) exit(1) filename = basename(argv[2]) dirs = argv[2].replace(filename,'') makedirs(dirs) copyfile(argv[1],argv[2])
这样做:
$ ./mkdircp.py /etc/passwd $HOME/foodir/bardir/passwd.copy $ stat --printf "%F\n" $HOME/foodir/bardir/passwd.copy regular file $ head -n 1 $HOME/foodir/bardir/passwd.copy root:x:0:0:root:/root:/bin/bash
您可以使用;轻松键入两个命令。 例如:
mkdir folder; cp file.html folder
它应该工作。