#!/bin/bash
# 检查参数个数
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory_path>"
exit 1
fi
directory=$1
results=()
lockfile=$(mktemp)
max_threads=10
thread_count=0
# 定义处理文件的函数
process_file() {
local file=$1
local result=$(grep "特定字符串" $file 2>/dev/null)
if [ $? -eq 0 ]; then
# 使用锁来防止并发写入冲突
flock -x $lockfile
results+=("$file: $result")
flock -u $lockfile
fi
}
# 递归遍历目录
find $directory -type f -name "*.txt" | while read -r file; do
while [ $thread_count -ge $max_threads ]; do
# 等待有线程完成
wait -n
thread_count=$((thread_count - 1))
done
process_file $file &
thread_count=$((thread_count + 1))
done
# 等待所有线程完成
wait
# 输出结果
echo "处理结果汇总:"
for result in "${results[@]}"; do
echo $result
done
# 删除临时锁文件
rm $lockfile