3つのフォルダがあります:
- フォルダ現在 、現在のファイルが含まれています
- フォルダ古い 、同じファイルの古いバージョンが含まれています
- フォルダ違い 、これは単なる空のフォルダです
古いをどのように比較しますか 現在 現在で異なる(またはまったく新しい)ファイルをコピーします 違いへ ?
私はあちこちを検索していて、取り組むのは簡単なことのように思えますが、私の特定の例ではそれを機能させることができません。ほとんどの情報源は、 rsyncの使用を提案しました そのため、次のコマンドを実行することになりました。
rsync -ac --compare-dest=../old/ new/ difference/
ただし、これは、新規からすべてのファイルをコピーします。 違いへ 、古いと同じものでも 。
それが役立つ場合(おそらくコマンドは問題なく、障害は他の場所にあります)、これは私がこれをテストした方法です:
- 3つのフォルダを作成しました。
- 古いで内容の異なるテキストファイルをいくつか作成しました 。
- 古いからファイルをコピーしました 新規へ 。
- newの一部のファイルの内容を変更しました いくつかのファイルを追加しました。
- 上記のコマンドを実行し、結果を違いで確認しました 。
私は過去数日間解決策を探していましたが、助けていただければ幸いです。必ずしもrsyncを使用している必要はありませんが、可能であれば、私が間違っていることを知りたいのです。
承認された回答:
rsyncやdiffなどの既存のLinuxコマンドでそれを実行できるかどうかはわかりません。しかし、私の場合、Pythonにはファイル比較用の「filecmp」モジュールがあるため、Pythonを使用して独自のスクリプトを作成する必要がありました。スクリプト全体と使用法を個人用サイト(http://linuxfreelancer.com/
)に投稿しました。使い方は簡単です。新しいディレクトリ、古いディレクトリ、差分ディレクトリの絶対パスをこの順序で指定してください。
#!/usr/bin/env python
import os, sys
import filecmp
import re
from distutils import dir_util
import shutil
holderlist = []
def compareme(dir1, dir2):
dircomp = filecmp.dircmp(dir1, dir2)
only_in_one = dircomp.left_only
diff_in_one = dircomp.diff_files
dirpath = os.path.abspath(dir1)
[holderlist.append(os.path.abspath(os.path.join(dir1, x))) for x in only_in_one]
[holderlist.append(os.path.abspath(os.path.join(dir1, x))) for x in diff_in_one]
if len(dircomp.common_dirs) > 0:
for item in dircomp.common_dirs:
compareme(
os.path.abspath(os.path.join(dir1, item)),
os.path.abspath(os.path.join(dir2, item)),
)
return holderlist
def main():
if len(sys.argv) > 3:
dir1 = sys.argv[1]
dir2 = sys.argv[2]
dir3 = sys.argv[3]
else:
print "Usage: ", sys.argv[0], "currentdir olddir difference"
sys.exit(1)
if not dir3.endswith("/"):
dir3 = dir3 + "/"
source_files = compareme(dir1, dir2)
dir1 = os.path.abspath(dir1)
dir3 = os.path.abspath(dir3)
destination_files = []
new_dirs_create = []
for item in source_files:
destination_files.append(re.sub(dir1, dir3, item))
for item in destination_files:
new_dirs_create.append(os.path.split(item)[0])
for mydir in set(new_dirs_create):
if not os.path.exists(mydir):
os.makedirs(mydir)
# copy pair
copy_pair = zip(source_files, destination_files)
for item in copy_pair:
if os.path.isfile(item[0]):
shutil.copyfile(item[0], item[1])
if __name__ == "__main__":
main()