|
@@ -11,22 +11,39 @@ if [ ! -d "$dir" ]; then
|
|
|
exit 1
|
|
|
fi
|
|
|
|
|
|
-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)
|
|
|
+# 设置变量n表示查找字符串的次数
|
|
|
+n=1
|
|
|
+file=""
|
|
|
+while [ -z "$file" ] && [ "$n" -le 5 ]; do
|
|
|
+ # 如果$3为空,则查找以"error"开头的文件;否则查找不包含"$3"的文件
|
|
|
+ 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
|
|
|
+ # 如果找到了字符串,则跳出循环
|
|
|
+ break
|
|
|
+ fi
|
|
|
+
|
|
|
+ # 如果没有找到字符串,则增加计数器并继续查找下一个文件
|
|
|
+ n=$((n+1))
|
|
|
+done
|
|
|
|
|
|
if [ -z "$matching_line" ]; then
|
|
|
- echo "文件 $file 中没有找到字符串 '$2'"
|
|
|
+ echo "在前5个文件中没有找到字符串 '$2'"
|
|
|
exit 1
|
|
|
+else
|
|
|
+ echo "在文件 $file 的第 $matching_line 行找到了字符串 '$2'"
|
|
|
fi
|
|
|
|
|
|
line_number=$(echo "$matching_line" | cut -d ":" -f 1)
|