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

如何在Linux下用bash/Python/awk复现SAS按chr字段合并两文件的逻辑

你需要的按chr字段的内连接(同chr行两两组合匹配)完全可以通过bash、Python等工具实现,以下是两种常用的可直接运行的实现方案:


方案1:awk 实现(bash原生工具,无需额外安装,适合大文件处理)

逻辑为先加载map文件按chr分组存储所有行,再遍历amer_chr文件输出对应匹配的所有关联行:

NR==FNR {
    # 处理第一个输入文件map
    if(FNR==1) map_header = $0;
    else map[$1] = map[$1] "\n" $0;
    next
}
FNR==1 {
    # 输出合并后的表头
    print $0, map_header;
    next
}
$1 in map {
    # 匹配到chr则输出当前amer_chr行+所有匹配的map行
    split(map[$1], line_arr, "\n");
    for(i in line_arr){
        if(line_arr[i] != "") print $0, line_arr[i]
    }
}

运行命令(注意文件顺序,map在前,amer_chr在后):

awk -f join.awk map amer_chr > both_amer_chr.txt

方案2:Python pandas 实现(逻辑清晰易维护,适合需要后续加工数据的场景)
import pandas as pd

# 读取两个文件,sep="\s+"自动适配空格、多空格、tab分隔的文本
amer_chr = pd.read_csv("amer_chr", sep="\s+")
map_df = pd.read_csv("map", sep="\s+")

# 按chr字段做内连接,逻辑和SAS代码完全一致
both_amer_chr = pd.merge(amer_chr, map_df, on="chr", how="inner")

# 输出结果,不保留索引列
both_amer_chr.to_csv("both_amer_chr.txt", sep=" ", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:24:04