You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python重现指定BASH脚本的文件检索与内容匹配逻辑

用Python重现指定Bash脚本的功能

需求对应Bash脚本逻辑拆解

你提供的Bash脚本核心逻辑如下:

  • 列出/dir下所有符合some_file_${VARIABLE}_*.log命名规则的文件,按修改时间升序排列
  • 筛选出最新修改的2个文件(升序排列后取最后2个)
  • 在这两个文件中查找包含指定字符串的行并输出
  • 需要处理文件不存在、无匹配文件的异常情况

完整Python实现代码

import os
import glob

def search_logs(dir_path, variable, search_string):
    # 匹配符合命名规则的日志文件
    pattern = os.path.join(dir_path, f"some_file_{variable}_*.log")
    matching_files = glob.glob(pattern)
    
    if not matching_files:
        print("未找到符合规则的日志文件")
        return
    
    # 按文件修改时间升序排序(对应Bash的ls -1tr)
    sorted_files = sorted(matching_files, key=lambda x: os.path.getmtime(x))
    # 取最新的2个文件(对应Bash的tail -2),文件不足2个时取全部
    target_files = sorted_files[-2:] if len(sorted_files) >= 2 else sorted_files
    
    for file_path in target_files:
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    if search_string in line:
                        print(line.strip())
        except FileNotFoundError:
            print(f"警告:文件 {file_path} 已不存在,跳过")
        except Exception as e:
            print(f"读取文件 {file_path} 时出错:{str(e)}")

# 示例调用,替换为你的实际参数
if __name__ == "__main__":
    DIR_PATH = "/dir"
    VARIABLE = "your_variable_here"
    SEARCH_STRING = "SEARCH STRING"
    search_logs(DIR_PATH, VARIABLE, SEARCH_STRING)

代码关键部分解释

  1. 文件匹配:用glob.glob匹配指定目录下的目标文件,os.path.join解决跨平台路径拼接问题
  2. 排序逻辑:通过os.path.getmtime获取文件修改时间,按升序排序后取最后2个,和Bash脚本的ls -1tr | tail -2逻辑完全对齐
  3. 异常处理:
    • 无匹配文件时直接给出提示
    • 遍历文件时捕获FileNotFoundError,处理文件在检索过程中被删除的情况
    • 捕获其他通用异常,避免程序意外崩溃
  4. 字符串查找:逐行读取文件内容,判断目标字符串是否存在,输出匹配行(和grep核心逻辑一致)

内容的提问来源于stack exchange,提问作者Scott Zuris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 14:15:41