![](/img/trans.png)
[英]Linux bash How to use a result of a wildcard as a file name in a copy command
[英]How to copy a file to a folder if there is already a file with the same name (Linux BASH)
例如,如果我创建了一个垃圾箱文件夹,并且其中已经有~/dustbin/File01
,我如何将新文件复制到同名文件夹中?
例如:
cp ~/test/File01 ~/dustbin/File01
但是,请在其末尾添加(复制)
Unix文件系统不允许在同一文件夹中使用两个具有相同名称的文件(作为参考,VMS允许这样做)。
您可以将cat
与append配合使用:
cat ~/test/File01 >> ~/dustbin/File01
当文件不存在或追加到现有文件时,将创建该文件。
cp
命令还提供了进行备份的选项,因此它不会覆盖现有文件。 参见--backup
选项。
我想您是在询问如何检测文件是否已存在,然后重命名新文件,以使其不会被覆盖。 在这种情况下:
if [[ -f "$HOME/dustbin/File01" ]]; then
cp "$HOME/test/File01" "$HOME/dustbin/File01 (Copy)"
else
cp "$HOME/test/File01" "$HOME/dustbin/File01"
fi
实际上就是您要的。 您可以更一般地执行此操作:
if [[ -f "$dest" ]]; then
cp "$source" "${dest%/*}/${dest##*/} (Copy)"
else
cp "$source" "$dest"
fi
但是,如果不小心使用文件名,则冒着在文件名中包含“(复制)(复制)(复制)(复制)…”的风险。
dd if=~/test/File01 >> ~/dustbin/File01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.