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

如何将包含awk命令的bash脚本转换为可正常运行的Python3脚本

Bash脚本转Python3实现方案

原Bash脚本的功能逻辑如下:

  • 接收series变量作为输入参数
  • 第一步:从Sys_${series}.txt中提取第4列内容,筛选匹配Y*.正则规则的内容,排序去重后写入Pri${series}.txt
  • 第二步:统计Sys_${series}.txt中第4列内容在Pri${series}.txt中的出现次数,按key排序后写入Result_${series}.txt

对应Python3实现代码

import sys
import re
from collections import defaultdict

def main():
    # 校验入参,需要传入series变量
    if len(sys.argv) < 2:
        print("使用方式: python3 脚本名.py <series值>")
        sys.exit(1)
    series = sys.argv[1]
    
    # 定义文件名
    final_file = f"Sys_{series}.txt"
    f_final_file = f"Pri{series}.txt"
    result_file = f"Result_{series}.txt"

    # 对应原脚本第一步逻辑:提取符合规则的第4列去重排序
    match_pattern = re.compile(r'Y*\.')
    valid_keys = set()
    with open(final_file, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            cols = line.split()
            if len(cols) < 4:
                continue
            col4 = cols[3]
            if match_pattern.search(col4):
                valid_keys.add(col4)
    sorted_valid_keys = sorted(valid_keys)
    with open(f_final_file, 'w', encoding='utf-8') as f:
        for key in sorted_valid_keys:
            f.write(f"{key}\n")

    # 对应原脚本第二步逻辑:统计匹配项的出现次数
    count_map = defaultdict(int)
    for key in sorted_valid_keys:
        count_map[key] = 0
    with open(final_file, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            cols = line.split()
            if len(cols) < 4:
                continue
            col4 = cols[3]
            if col4 in count_map:
                count_map[col4] += 1
    # 排序后写入结果文件
    sorted_result = sorted(count_map.items(), key=lambda x: x[0])
    with open(result_file, 'w', encoding='utf-8') as f:
        for key, cnt in sorted_result:
            f.write(f"{key}: Total ={cnt}\n")

if __name__ == "__main__":
    main()

使用说明

  • 保存上述代码为convert.py
  • 执行命令:python3 convert.py 你的series值即可得到对应输出文件
  • 如果你的源文件是非utf-8编码,修改代码中open函数的encoding参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:06:03