gpt4 book ai didi

awk 提取并打印第一次出现的模式

转载 作者:行者123 更新时间:2023-12-01 09:13:06 25 4
gpt4 key购买 nike

我正在尝试使用 awk 来提取和打印第一次出现的 NM_ 以及 NP_ 之后以 开头的部分p.. : 被打印而不是“|”对于每个。输入文件是 tab-delimeted,但输出不需要。下面确实执行但打印文件中的所有行而不仅仅是模式。在我超过 5000 行的实际数据中可能有多个 NMNP,但是只提取和打印每个的第一次出现。我对 RSTARTRLENGHTH 概念还是有点不清楚,但是,以输入中的第 1 行为例:

NM 变量将是 NM_020469.2

NP 变量将是 :p.Gly268Arg

我也包含了评论。谢谢 :)。

输入

Input Variant   HGVS description(s) Errors and warnings
rs41302905 NC_000009.11:g.136131316C>T|NM_020469.2:c.802G>A|NP_065202.2:p.Gly268Arg
rs8176745 NC_000009.11:g.136131347G>A|NM_020469.2:c.771C>T|NP_065202.2:p.Pro257=

期望的输出

rs41302905 NM_020469.2:c.802G>A:p.Gly268Arg
rs8176745 NM_020469.2:c.771C>T:p.Pro257=

awk -F'[\t|]' 'NR>1{ # define FS as tab and `|` to split each, and skip header line
r=$1; nm=np=""; # create variable r with $1 and 2 variables (one for nm and the other for np, setting them to null)
for(i=2;i<=NF;i++) { # start a loop from line2 and itterate
if ($i~/^NM_/) nm=$i; # extract first NM_ in line and read into i
else if ($i~/^NP_/) np=substr($i,index($i,":")); # extract NP_ and print portion after : (including :)
if (nm && np) { print r,nm np; break } # print desired output
}
}' input

最佳答案

Awk解决方案:

awk -F'[\t|]' 'NR>1{
r=$1; nm=np="";
for(i=2;i<=NF;i++) {
if ($i~/^NM_/) nm=$i;
else if ($i~/^NP_/) np=substr($i,index($i,":"));
if (nm && np) { print r,nm np; break }
}
}' input

  • 'NR>1 - 从第二条记录开始处理

  • r=$1; nm=np="" - 所需变量的初始化

  • for(i=2;i<=NF;i++) - 遍历字段(从第 2 个开始)

  • if ($i~/^NM_/) nm=$i - 捕获 NM_...项目进入 variale nm

  • else if ($i~/^NP_/) np=substr($i,index($i,":")) - 捕获 NP_...项目进入 variale np (从:开始到结束)

  • if (nm && np) { print r,nm np; break } - 如果两个项目都已被捕获 - 打印它们并中断循环以避免进一步处理


输出:

rs41302905 NM_020469.2:c.802G>A:p.Gly268Arg
rs8176745 NM_020469.2:c.771C>T:p.Pro257=

关于awk 提取并打印第一次出现的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46524804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com