抱歉,如果我错过了cp
手册中的某些内容,但是是否可以将文件复制到可能存在相同名称的文件的目录中?如果目标目录中有一个具有相同名称的文件,则类似于在复制文件的名称中添加后缀。就像是:
ls foo
file
cp file foo/
ls foo
file
file*
我正在运行的操作系统是Ubuntu Gnu / Linux。
如果已经使用目标名称,则在目标名称上添加一个正整数,并递增该整数直到找到一个免费名称:
mycp () {
local source="$1"
local target="$2"
local n
# If the target pathname is a directory, add the source filename
# the end of it.
if [ -d "$target" ]; then
target+="/$(basename "$source")"
fi
# Increment n until a free name is found
# (this may leave n unset if the source filename is free).
while [ -e "$target$n" ]; do
n=$(( n + 1 ))
done
cp "$source" "$target$n"
}
注意:除了源路径名和目标路径名外,此函数不接受任何其他参数。它还假定您正在使用bash
外壳程序。
要“安装”它,只需在外壳程序中运行以上代码,或将其添加到通常添加别名和函数的位置即可。
测试:
$ ls
dir file
$ ls dir/
$ mycp file dir
$ ls dir/
file
$ mycp file dir
$ ls dir/
file file1
$ mycp file dir
$ ls dir/
file file1 file2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句