shell 两两比较文件

p5cysglq  于 2022-11-16  发布在  Shell
关注(0)|答案(2)|浏览(115)

我需要比较文件夹中的文件,现在我手动浏览它们并运行:

diff -w file1 file2 > file_with_difference

我怎样才能一次比较它们两个呢?下面的代码(伪代码)会让我的生活变得更轻松:

for eachfile in folder:
    diff -w filei filei+1 > file_with_differencei #the position of the file, because the name can vary randomly
                                                  
    i+=1                                          #so it goes to 3vs4 next time through the loop, 
                                                  #and not 2vs3

因此,它比较第1和第2,第3-第4,以此类推。文件夹总是有偶数个文件。

rt4zxlrg

rt4zxlrg1#

假设globe按您希望的顺序列出文件:

declare -a list=( folder/* )

for (( i = 0; i < ${#list[@]}; i += 2 )); do
  if [[ -f "${list[i]}" ]] && [[ -f "${list[i + 1]}" ]]; then
    diff "${list[i]}" "${list[i + 1]}" > "file_with_difference_$i"
  fi
done
dw1jzc5e

dw1jzc5e2#

@Renaud有一个很棒的答案。
假设您的文件名不包含空格,则可以使用以下替代方法:

printf '%s %s\n' * |
  while read -r f1 f2; do
    diff "$f1" "$f2" > "diffs_$((++i))"
  done

相关问题