【问题标题】:Is there a way tp go through files and comparing them two by two in bash script?有没有办法通过文件并在 bash 脚本中两两比较它们?
【发布时间】:2022-10-17 21:20:45
【问题描述】:

我是 bash 脚本的新手,所以我认为可能有办法做到这一点,但我无法在网上找到我想要的信息。

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

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

所以它将 1st 与 2nd、3rd-4th 进行比较,依此类推。 该文件夹总是有偶数个文件。

非常感谢!

【问题讨论】:

  • 我不明白您如何选择要比较的文件对?如果我的文件夹包含config.inidata.yamlmain.gooutput.json,我应该将config.inidata.yaml 进行比较,然后将main.gooutput.json 进行比较?
  • 是的,文件夹结构已经建立,文件是成对的,new_file_id_date - old_file_id_date。任务是找出文件的两个版本之间的差异。
  • fwiw : 如果你打算比较同一目录的两个版本,你也可以设置两个目录,old/new/,文件有完全相同的名字在他们两个中,只需运行diff old new

标签: bash shell scripting compare


【解决方案1】:

假设 globing 按您想要的顺序列出文件:

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

【讨论】:

  • 非常感谢!您节省了大量的体力劳动
【解决方案2】:

假设您的文件名不包含空格。

@Renaud 有一个很好的答案。

替代

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

【讨论】:

  • 为什么不printf '%s %s ' * 保存paste
  • 因为我喜欢粘贴?不,这是一个很好的建议。
  • 请注意,要处理花哨的文件名,我们还可以使用 NUL: declare -i i=0; printf '%s
猜你喜欢
  • 2022-10-18
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多