bash - 您将如何遍历目录中的文件并将它们相互比较?
问题描述
我从不编写 bash 脚本,所以我不知道最有效且快速的方法。我知道我会如何在 python 或 c++ 之类的东西中做到这一点。
我有一个文件结构,如下所示:
-parentDir
--subDir1
---file1.txt
---file2.txt
---file3.txt
---file4.txt
--subDir2
---file1.txt
---file2.txt
---file3.txt
---file4.txt
可以有任意数量的子目录和文本文件。
基本上,我想创建一个进入每个子目录的 bash 脚本,然后使用file1.txt
和file2.txt
使用 diff 进行比较,然后进行比较file2.txt
,file3.txt
依此类推,将差异输出到 txt 文件的末尾。
我知道如何使用 diff 来比较文件,然后将差异输出到 txt 文件我只是不知道如何做我设想的双 for 循环。
有任何想法吗?
解决方案
#!/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
推荐阅读
- python - pyinstaller 编译的 .exe 什么都不做
- python - 使用 BeautifulSoup 抓取自定义 ebay 搜索。如何处理分页?
- asp.net - 中继器的手风琴中没有显示数据
- javascript - 如何从列表中删除文件(图像)?
- windows - 在 Windows 中删除具有相同名称但不同文件扩展名的文件差异的最快方法
- javascript - 如何将元素添加到对象中以及如何在 javascript 中测试复杂对象中值的存在?
- spring-cloud - 问题测试spring cloud SQS Listener
- python - GitPython 检查 git pull 是否更改了本地文件
- java - Java - 具有泛型类参数的构造函数
- sql - SQL查询以获取每天的最大值