#!/bin/bash # $1:文件夹名称 # $2:匹配字符串 # $3:可选参数,文件名不包含此参数 dir="/logs/$1" if [ ! -d "$dir" ]; then echo "目录 $dir 不存在" exit 1 fi if [ -z "$3" ]; then file=$(ls -t "$dir" | grep "error" | head -n 1) else file=$(ls -t "$dir" | grep -v "$3" | head -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'" exit 1 fi line_number=$(echo "$matching_line" | cut -d ":" -f 1) echo "在文件 $file 中找到了字符串 '$2',位于第 $line_number 行:" sed -n "$((line_number - 50)),$((line_number + 100))p" "$dir/$file" | awk '{printf("%s %s\n", NR+'$(($line_number - 51))', $0)}' echo "在文件 $file 中找到了字符串 '$2',位于第 $line_number 行:"