使用'diff'与不匹配的目录和文件名

时间:2015-01-16 21:47:15

标签: shell diff

我有两个单独的文件夹目录,它们大多包含相同的文件,但两个文件夹之间的目录结构完全不同。文件名不对应

所以,例如:

FOLDER 1
--- Subfolder A
    -file1
    -file2
--- Subfolder B
    -file3
    -file4

FOLDER 2
--- Subfolder C
    -Subfolder C1
        -file5
        -file6
        -file7
    -Subfolder C2
        -file8
        -file9

我们假设file1=file5file2=file6file3=file7file4=file8 file9是无与伦比的。

diff命令是否有一些选项组合可以识别匹配?使用diff执行递归-r似乎无法完成此任务。

2 个答案:

答案 0 :(得分:1)

这是一种通过findxargs获取不同和/或相同文件的方法:

find FOLDER1 -type f -print0 |
xargs -0 -I % find FOLDER2 -type f -exec diff -qs --from-file="%" '{}' \+

示例输出:

  

文件FOLDER1 / SubfolderB / file3和FOLDER2 / SubfolderC / SubfolderC1 / file5不同
  文件FOLDER1 / SubfolderB / file3和FOLDER2 / SubfolderC / SubfolderC1 / file7完全相同

因此,您可以使用grep过滤所需的内容(请参阅示例)。

请注意,此解决方案支持嵌入空格和特殊字符(例如:换行符)的文件名,因此您不必担心

解释

对于FOLDER1find FOLDER1 -type f -print0)中的每个文件,执行:

find FOLDER2 -type f -exec diff -qs --from-file="%" '{}' \+

该行再次调用find以获取FOLDER2中的所有文件并执行以下(已处理):

diff -qs --from-file="<a file from FOLDER1>" <all the files from FOLDER2>

来自man diff

  

- 从文件= FILE1
      将FILE1与所有操作数进行比较。 FILE1可以是目录。

实施例

这是目录树和文件内容:

$ find FOLDER1 FOLDER2 -type f -exec sh -c 'echo "$0": &&  cat "$0"' '{}' \;
FOLDER1/SubfolderA/file1:
1=5
FOLDER1/SubfolderA/file2:
2=6
FOLDER1/SubfolderB/file3:
3=7
FOLDER1/SubfolderB/file4:
4=8
FOLDER2/SubfolderC/SubfolderC1/file5:
1=5
FOLDER2/SubfolderC/SubfolderC1/file6:
2=6
FOLDER2/SubfolderC/SubfolderC1/file7:
3=7
FOLDER2/SubfolderC/SubfolderC2/file8:
4=8
FOLDER2/SubfolderC/SubfolderC2/file9:
anything

这是命令(管道)只获得相同的

$ find FOLDER1 -type f -print0 |
> xargs -0 -I % find FOLDER2 -type f -exec diff -qs --from-file="%" '{}' \+ |
> grep "identical$"
Files FOLDER1/SubfolderA/file1 and FOLDER2/SubfolderC/SubfolderC1/file5 are identical
Files FOLDER1/SubfolderA/file2 and FOLDER2/SubfolderC/SubfolderC1/file6 are identical
Files FOLDER1/SubfolderB/file3 and FOLDER2/SubfolderC/SubfolderC1/file7 are identical
Files FOLDER1/SubfolderB/file4 and FOLDER2/SubfolderC/SubfolderC2/file8 are identical

使用bash&#39; Process SubstitutionArrays

的增强型解决方案

如果您正在使用bash,则可以先将所有FOLDER2个文件名保存在数组中,以避免为find中的每个文件调用FOLDER1:< / p>

# first of all, we save all the FOLDER2 filenames (recursively) in an array
while read -d $'\0' file; do
    folder2_files=("${folder2_files[@]}" "$file")
done < <(find FOLDER2 -type f -print0)
# now we compare each file in FOLDER1 with the files in the array
find FOLDER1 -type f -exec diff -qs --from-file='{}' "${folder2_files[@]}" \; |
grep "identical$"

答案 1 :(得分:0)

创建一个临时Git存储库。将第一个目录树添加到其中,然后提交。

删除所有文件并将第二个目录树添加到其中。做第二次提交。

这两个提交之间的git diff将打开重命名检测,你可能会看到更具吸引力的东西。