【问题标题】:How would you loop through files in a directory and compare them to each other?您将如何遍历目录中的文件并将它们相互比较?
【发布时间】:2019-07-31 23:52:49
【问题描述】:

我从不编写 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 循环。

有什么想法吗?

【问题讨论】:

  • 这不是双 for 循环。您只是将每个文件与下一个文件进行比较,而不是与所有其他文件进行比较。还是你描述错了?
  • 总是只有 2 层嵌套,还是必须递归地进行任何深度?
  • 也许你可以向我们展示你将如何在 python 中做到这一点。因为否则您的描述缺乏清晰性(您是否应该跨子目录比较文件?,是否只有文本文件?文本文件是否总是具有相同的 .txt 后缀?在哪里输出差异,用什么名称......)
  • 我只是想双倍因为我看到它类似于“对于每个 dir 父目录,然后对于 dir 中的每个文件比较下一个文件”@Bamar
  • 将文件名放入数组中,然后可以遍历数组索引,并使用diff ${array[$i]} ${array[$i+1]}

标签: bash shell diff


【解决方案1】:
#!/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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多