cpファイルを同じ名前のファイルがあるディレクトリにコピーする

cpファイルを同じ名前のファイルがあるディレクトリにコピーする

cpマニュアルで何かを逃した場合は申し訳ありません。しかし、同じ名前のファイルが存在する可能性があるディレクトリにファイルをコピーする方法はありますか?たとえば、ターゲットディレクトリに同じ名前のファイルがある場合は、コピーしたファイル名にサフィックスを追加します。それは次のとおりです。

ls foo
    file
cp file foo/
ls foo
    file
    file* 

私が使用しているオペレーティングシステムはUbuntu Gnu / Linuxです。

ベストアンサー1

名前がすでに使用されている場合は、ターゲット名に正の整数を追加し、使用可能な名前が見つかるまで整数を増やします。

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

おすすめ記事