wangzhiyong 1 year ago
parent
commit
078ca4e466
1 changed files with 15 additions and 24 deletions
  1. 15 24
      log.sh

+ 15 - 24
log.sh

@@ -5,50 +5,41 @@
 # $3:可选参数,文件名不包含此参数
 
 dir="/logs/$1"
+count=0
 
 if [ ! -d "$dir" ]; then
   echo "目录 $dir 不存在"
   exit 1
 fi
 
-# 设置变量n表示查找字符串的次数
-n=1
-file=""
-while [ -z "$file" ] && [ "$n" -le 5 ]; do
-  # 如果$3为空,则查找以"error"开头的文件;否则查找不包含"$3"的文件
+while [ $count -lt 5 ]
+do
   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 [ -n "$matching_line" ]; then
-    # 如果找到了字符串,则跳出循环
+  if [ -z "$matching_line" ]; then
+    echo "文件 $file 中没有找到字符串 '$2'"
+    count=$((count+1))
+  else
+    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)}'
     break
   fi
-
-  # 如果没有找到字符串,则增加计数器并继续查找下一个文件
-  n=$((n+1))
 done
 
-if [ -z "$matching_line" ]; then
-  echo "在前5个文件中没有找到字符串 '$2'"
+if [ $count -eq 5 ]; then
+  echo "在目录 $dir 中的多个文件中都没有找到字符串 '$2'"
   exit 1
-else
-  echo "在文件 $file 的第 $matching_line 行找到了字符串 '$2'"
 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 行:"