首页 > 解决方案 > 您将如何遍历目录中的文件并将它们相互比较?

问题描述

我从不编写 bash 脚本,所以我不知道最有效且快速的方法。我知道我会如何在 python 或 c++ 之类的东西中做到这一点。

我有一个文件结构,如下所示:

-parentDir
   --subDir1
      ---file1.txt
      ---file2.txt
      ---file3.txt
      ---file4.txt
   --subDir2
      ---file1.txt
      ---file2.txt
      ---file3.txt
      ---file4.txt

可以有任意数量的子目录和文本文件。

基本上,我想创建一个进入每个子目录的 bash 脚本,然后使用file1.txtfile2.txt使用 diff 进行比较,然后进行比较file2.txtfile3.txt依此类推,将差异输出到 txt 文件的末尾。

我知道如何使用 diff 来比较文件,然后将差异输出到 txt 文件我只是不知道如何做我设想的双 for 循环。

有任何想法吗?

标签: bashshelldiff

解决方案


#!/usr/bin/env bash

typeset -r diffs=diffs.txt
typeset -a allfiles=()
typeset -- filename=''

# fills the allfiles array with all *.txt files except the diffs.txt
# that can be found from the current directory and down all sub-directories
while IFS= read -r -d '' filename; do
  allfiles+=("$filename")
done < <(
  find . -type f -name '*.txt' -and -not -name "$diffs" -print0 2>/dev/null
)

[[ ${#allfiles[@]} -lt 2 ]] && exit 2 # Need at least 2 files to compare

typeset -i i=0 j=0
typeset -- file_a='' file_b=''
export LC_MESSAGES=POSIX
# for all files except last
for ((i = 0; i < ${#allfiles[@]} - 1; i++)); do
  file_a="${allfiles[$i]}"
  # for next file to last file
  for ((j = i + 1; j < ${#allfiles[@]}; j++)); do
    file_b="${allfiles[$j]}"
    diff --report-identical-files --unified=0 --minimal -- \
      "$file_a" "$file_b" 2>/dev/null
    echo
  done
done >"$diffs" # all output to the diffs file

推荐阅读