使用Awk将选定行转置为列:处理指定格式的术语文本文件
使用Awk将HP术语行转置为列的实现方法
针对你提供的HP术语文本格式,我们可以用Awk编写脚本,将每个[Term]块中的分散行转换为一行多列的格式,同时处理多个alt_id条目并合并到同一列中。
实现思路
- 以
[Term]作为每个术语块的起始标记,遇到新的[Term]时先输出上一个术语的结果,再重置变量。 - 分别捕获
id、name、多个alt_id和def字段的值。 - 将多个
alt_id用逗号分隔合并为一个字符串。 - 处理
def字段时,提取引号内的定义文本。 - 最后输出所有术语的结构化结果。
Awk脚本代码
BEGIN { # 设置输出分隔符为制表符(方便导入表格工具) OFS = "\t" # 打印表头(可选,根据需要调整) print "ID", "名称", "替代ID", "定义" } # 遇到新的术语块时,先输出上一个术语的数据 /^\[Term\]/ { if (id != "") { print id, name, alt_ids, def } # 重置变量 id = "" name = "" alt_ids = "" def = "" next } # 捕获ID字段 /^id:/ { id = $2 next } # 捕获名称字段(处理带空格的名称) /^name:/ { name = substr($0, index($0, $2)) next } # 捕获并合并多个替代ID /^alt_id:/ { if (alt_ids != "") alt_ids = alt_ids ", " alt_ids = alt_ids $2 next } # 捕获定义字段(提取引号内的内容) /^def:/ { start = index($0, "\"") + 1 end = index(substr($0, start), "\"") + start - 1 def = substr($0, start, end - start) next } # 处理最后一个术语块 END { if (id != "") { print id, name, alt_ids, def } }
使用方法
- 将上述脚本保存为
transpose_hp.awk文件。 - 执行以下命令处理你的输入文件(假设输入文件名为
hp_terms.txt):
awk -f transpose_hp.awk hp_terms.txt > hp_terms_transposed.tsv
- 输出文件
hp_terms_transposed.tsv是制表符分隔的表格,可直接用Excel、Numbers等工具打开。
示例效果
输入片段:
[Term] id: HP:0000006 name: Autosomal dominant inheritance alt_id: HP:0001415 alt_id: HP:0001447 def: "A mode of inheritance that is observed for traits related to a gene encoded on one of the autosomes..."
输出行(制表符分隔):
HP:0000006 Autosomal dominant inheritance HP:0001415, HP:0001447 A mode of inheritance that is observed for traits related to a gene encoded on one of the autosomes...
注意事项
- 如果
def字段的文本跨多行,需要修改脚本以处理多行内容(当前脚本假设每个字段都在单行)。 - 可根据需求调整输出分隔符(如将
OFS = "\t"改为OFS = ","生成CSV文件)。
内容的提问来源于stack exchange,提问作者gungu
相关产品推荐
相关产品推荐

