打印 err 相关的前后10行
跳到导航
跳到搜索
shell
#!/bin/bash file="your_log_file.log" # 使用grep找到包含err的行号 line_numbers=$(grep -n "err" $file | cut -d: -f1) for num in $line_numbers; do start=$((num - 10)) end=$((num + 10)) if [ $start -lt 1 ]; then start=1 fi sed -n "${start},${end}p" $file echo "------------------------" done
py
def print_lines_around_err(file_path): with open(file_path, 'r', encoding='utf-8') as file: lines = file.readlines() for index, line in enumerate(lines): if 'err' in line: start_index = max(0, index - 10) end_index = min(len(lines), index + 11) for i in range(start_index, end_index): print(lines[i].strip()) print("-" * 50) # 用于分隔不同匹配处的内容 # 使用示例,替换成实际的文件路径 file_path = "your_file.txt" print_lines_around_err(file_path)