用 bash 脚本计算当前文件夹内所有 .docx 文件的 sha1 值

From 清冽之泉
Jump to navigation Jump to search

保存这段代码为 calc_sha1_input.sh,再./calc_sha1_input.sh 23333运行,就会计算出 calc_sha1_input.sh 所在文件夹内所有 .docx 文件的 sha1 值,并输出结果为 23333.txt。calc_sha1_input.sh 中的 input 是提示你,这段脚本需要输入一个参数,用以指定结果的文件名前缀。这对于当别人给你发了两个重复文件看着大差不差,但又不确定是否重复时很有用,只需要分别计算 sha1 值,再进 excel 表格中用 if 函数一比较就能清楚知道哪两个文件是一模一样的了。代码来自 Kimi.ai。

 1#!/bin/bash
 2
 3# 检查参数数量
 4if [ $# -ne 1 ]; then
 5    echo "Usage: $0 <prefix_for_result_file>"
 6    exit 1
 7fi
 8
 9# 提取结果文件前缀
10result_prefix="$1"
11
12# 确保结果文件名以.txt结尾
13if [[ "$result_prefix" != *.txt ]]; then
14    result_file="${result_prefix}.txt"
15else
16    echo "Error: Result filename should not include the .txt extension."
17    exit 1
18fi
19
20# 创建或清空指定的结果文件
21> "$result_file"
22
23# 遍历当前目录下的所有.docx文件
24for file in *.docx; do
25    # 检查文件是否存在
26    if [ -f "$file" ]; then
27        # 计算文件的SHA1哈希值
28        sha1=$(sha1sum "$file" | awk '{print $1}')
29        # 将哈希值和文件名写入指定的结果文件
30        echo "$sha1 $file" >> "$result_file"
31    fi
32done
33
34# 输出完成信息
35echo "SHA1 hashes have been written to $result_file"