log.sh 775 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/bin/bash
  2. # $1:文件夹名称
  3. # $2:匹配字符串
  4. # $3:可选参数,文件名不包含此参数
  5. dir="/logs/$1"
  6. if [ ! -d "$dir" ]; then
  7. echo "目录 $dir 不存在"
  8. exit 1
  9. fi
  10. if [ -z "$3" ]; then
  11. file=$(ls -t "$dir" | grep "error" | head -n 1)
  12. else
  13. file=$(ls -t "$dir" | grep -v "$3" | head -n 1 )
  14. fi
  15. if [ -z "$file" ]; then
  16. echo "目录 $dir 中没有符合要求的文件"
  17. exit 1
  18. fi
  19. matching_line=$(grep -n "$2" "$dir/$file" | tail -n 1)
  20. if [ -z "$matching_line" ]; then
  21. echo "文件 $file 中没有找到字符串 '$2'"
  22. exit 1
  23. fi
  24. line_number=$(echo "$matching_line" | cut -d ":" -f 1)
  25. echo "在文件 $file 中找到了字符串 '$2',位于第 $line_number 行:"
  26. sed -n "$((line_number - 50)),$((line_number + 100))p" "$dir/$file"