log.sh 618 B

123456789101112131415161718192021222324252627282930
  1. #!/bin/bash
  2. # $1:文件夹名称
  3. # $2:匹配字符串
  4. dir="/logs/$1"
  5. if [ ! -d "$dir" ]; then
  6. echo "目录 $dir 不存在"
  7. exit 1
  8. fi
  9. file=$(ls -t "$dir" | head -n 1)
  10. if [ -z "$file" ]; then
  11. echo "目录 $dir 中没有任何文件"
  12. exit 1
  13. fi
  14. matching_line=$(grep -n "$2" "$dir/$file" | tail -n 1)
  15. if [ -z "$matching_line" ]; then
  16. echo "文件 $file 中没有找到字符串 '$2'"
  17. exit 1
  18. fi
  19. line_number=$(echo "$matching_line" | cut -d ":" -f 1)
  20. echo "在文件 $file 中找到了字符串 '$2',位于第 $line_number 行:"
  21. sed -n "$((line_number - 50)),$((line_number + 100))p" "$dir/$file"