#!/bin/bash # $1:文件夹名称 # $2:匹配字符串 # $3:可选参数,文件名不包含此参数 dir="/logs/$1" count=0 if [ ! -d "$dir" ]; then echo "目录 $dir 不存在" exit 1 fi while [ $count -lt 5 ] do if [ -z "$3" ]; then file=$(ls -t "$dir" | grep "error" | head -n $((count + 1)) | tail -n 1) else file=$(ls -t "$dir" | grep -v "$3" | head -n $((count + 1)) | tail -n 1 ) fi if [ -z "$file" ]; then echo "目录 $dir 中没有符合要求的文件" exit 1 fi matching_line=$(grep -n "$2" "$dir/$file" | tail -n 1) if [ -z "$matching_line" ]; then echo "文件 $file 中没有找到字符串 '$2'" count=$((count+1)) else line_number=$(echo "$matching_line" | cut -d ":" -f 1) echo "在文件 $file 中找到了字符串 '$2',位于第 $line_number 行:" if [ $((line_number - 50)) -lt 0 ]; then sed -n "1,$((line_number + 100))p" "$dir/$file" | awk '{printf("%s %s\n", NR, $0)}' else sed -n "$((line_number - 50)),$((line_number + 100))p" "$dir/$file" | awk '{printf("%s %s\n", NR+'$(($line_number - 51))', $0)}' fi break fi done if [ $count -eq 5 ]; then echo "在目录 $dir 中的多个文件中都没有找到字符串 '$2'" exit 1 fi