如何循环遍历目录中的文件并获取它们之间的差异



这些是我的文件夹/文件:

backup/
├── folder1
│   ├── file1.txt
│   ├── file2.txt
│   └── file3.txt
└── folder2

file1.txt(为空)file2.txt(文件中只有X)File3(最后创建为空)

我的脚本:

#!/bin/sh
#config-checker.sh
#First loop looks at each folder in backup/. 
for j in `ls backup/  -1t` 
do
#change directory to other folders
cd backup/${j}/
N=0
#Grab the two newest files. Add them to an array called FILE
for i in `ls -1t | head -2`
do
FILE[$N]=$i
N=$N+1
done
#diff the two files in FILE
var=`diff ${FILE[0]} ${FILE[1]}`
#if a diff exists, show it
if [[ ${var} ]]
then
#script here takes two variables; the name of the folder and the content of the diff
echo $j "${var}"
fi
done

它没有得到文件上的差异,我的输出是这样的:

./config-checker.sh: 17: FILE[0]=file2: not found./config-checker.sh: 17: FILE[0+1]=file3: not found./config-checker.sh: 1:替换错误folder1./config-checker.sh: 11: cd: can't cd to backup/folder2./config-checker.sh: 17: FILE[0]=file2: not found./config-checker.sh: 17: FILE[0+1]=file3: not found./config-checker.sh: 1:替换错误folder2

不知道我错过了什么。任何帮助都会很感激。谢谢你

首先,我认为knittl评论说你没有从cd中返回是正确的。

第二,我已经编辑了我的回复。如果我现在理解正确的话,您想遍历一个文件夹的所有子文件夹。对于每个子文件夹,diff子文件夹中最近的两个文件,如果有两个,输出第一个文件的名称和diff。

为了完整起见,我把我的答案修改成我本来要写的,这与你原来的解决方案没有太大的不同:

topfolder=~/tmp/test
for folder in  $(ls -1t $topfolder)
do  
set --  $(ls -1t  $topfolder/$folder | head -2) 
if [ $# -ne 2 ] || diff -q $topfolder/$folder/$1 $topfolder/$folder/$2 > /dev/null
then
: # Do nothing
else
echo $1 
diff $topfolder/$folder/$1 $topfolder/$folder/$2
fi
done

作为差异点,我做了一个快速的困难找出是否有差异。通过这样做,我避免了在内存中保存可能无限数量的diff文本。是否值得采用这种方法取决于诸如差异的可能大小和循环可能执行的次数等因素。

最新更新