log.sh 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/bin/bash
  2. # $1:文件夹名称
  3. # $2:匹配字符串
  4. # $3:可选参数,文件名不包含此参数
  5. dir="/logs/$1"
  6. count=0
  7. if [ ! -d "$dir" ]; then
  8. echo "目录 $dir 不存在"
  9. exit 1
  10. fi
  11. while [ $count -lt 5 ]
  12. do
  13. if [ -z "$3" ]; then
  14. file=$(ls -t "$dir" | grep "error" | head -n $((count + 1)) | tail -n 1)
  15. else
  16. file=$(ls -t "$dir" | grep -v "$3" | head -n $((count + 1)) | tail -n 1 )
  17. fi
  18. if [ -z "$file" ]; then
  19. echo "目录 $dir 中没有符合要求的文件"
  20. exit 1
  21. fi
  22. matching_line=$(grep -n "$2" "$dir/$file" | tail -n 1)
  23. if [ -z "$matching_line" ]; then
  24. echo "文件 $file 中没有找到字符串 '$2'"
  25. count=$((count+1))
  26. else
  27. line_number=$(echo "$matching_line" | cut -d ":" -f 1)
  28. echo "在文件 $file 中找到了字符串 '$2',位于第 $line_number 行:"
  29. if [ $((line_number - 50)) -lt 0 ]; then
  30. sed -n "1,$((line_number + 100))p" "$dir/$file" | awk '{printf("%s %s\n", NR, $0)}'
  31. else
  32. sed -n "$((line_number - 50)),$((line_number + 100))p" "$dir/$file" | awk '{printf("%s %s\n", NR+'$(($line_number - 51))', $0)}'
  33. fi
  34. break
  35. fi
  36. done
  37. if [ $count -eq 5 ]; then
  38. echo "在目录 $dir 中的多个文件中都没有找到字符串 '$2'"
  39. exit 1
  40. fi