logr.sh 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 20 ]
  12. do
  13. if [ -z "$3" ]; then
  14. file=$(ls -rt "$dir" | grep "error" | tail -n $((20 - count)) | head -n 1)
  15. else
  16. file=$(ls -rt "$dir" | grep -v "$3" | tail -n $((20 - count)) | head -n 1 )
  17. fi
  18. if [ -z "$file" ]; then
  19. echo "目录 $dir 中没有符合要求的文件"
  20. exit 1
  21. fi
  22. matching_line=$( LC_ALL=C fgrep -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 - 100)) -lt 0 ]; then
  30. sed -n "1,$((line_number + 100))p" "$dir/$file" | awk '{printf("%s %s\n", NR, $0)}'
  31. echo "-----------------"
  32. command="sed -n \"1,$(( $line_number + 100 ))p\" \"$dir/$file\" | awk '{printf(\"%s %s\\n\", NR, \$0)}'"
  33. echo "$command"
  34. else
  35. sed -n "$((line_number - 100)),$((line_number + 100))p" "$dir/$file" | awk '{printf("%s %s\n", NR+'$(($line_number - 101))', $0)}'
  36. echo "-----------------"
  37. command="sed -n \"$(( $line_number - 100)),$(( $line_number + 100))p\" \"$dir/$file\" | awk '{printf(\"%s %s\\n\", NR+'$(($line_number - 101))', \$0)}'"
  38. echo "$command"
  39. fi
  40. echo "在文件 $file 中找到了字符串 '$2',位于第 $line_number 行:"
  41. break
  42. fi
  43. done
  44. if [ $count -eq 5 ]; then
  45. echo "在目录 $dir 中的多个文件中都没有找到字符串 '$2'"
  46. exit 1
  47. fi