awk - 打印行号(如 NR),但为 $3 中的每个新字段变量重新编号

标签 awk

使用 AWK 谁能告诉我如何打印类似于 NR 函数的字段,除了当在第 3 列($3)中看到新的“id”时重新开始编号。 使用命令 '{print $0 "\t"$3"-exon-"NR}' 对外显子 1 到 20 进行编号我想为字段 $3 中的每个新 id 重新重新编号(即.497097、19888、20671、18777 和 58175)。对于该文件,所有 ID 号都位于相邻行上。我在下面放了一个我尝试编码 $6 的格式示例。我的真实文件超过 250,000 行,并且有更多字段。我假设这真的很容易,但我一直无法找到正确的解决方案。
谢谢!

chr gene    id  start   stop    exon_number  
1   Xkr4    497097  3216021 3216967 497097-exon-1  
1   Xkr4    497097  3421701 3421900 497097-exon-2  
1   Xkr4    497097  3670551 3671347 497097-exon-3  
1   Rp1 19888   4344599 4350090 19888-exon-1    
1   Rp1 19888   4351909 4352080 19888-exon-2  
1   Rp1 19888   4352201 4352824 19888-exon-3  
1   Sox17   20671   4491715 4492667 20671-exon-1  
1   Sox17   20671   4493099 4493405 20671-exon-2  
1   Lypla1  18777   4807913 4807981 18777-exon-1  
1   Lypla1  18777   4808454 4808485 18777-exon-2  
1   Lypla1  18777   4828583 4828648 18777-exon-3  
1   Lypla1  18777   4830267 4830314 18777-exon-4  
1   Lypla1  18777   4832310 4832380 18777-exon-5  
1   Lypla1  18777   4837000 4837073 18777-exon-6  
1   Lypla1  18777   4839386 4839487 18777-exon-7  
1   Lypla1  18777   4840955 4841131 18777-exon-8  
1   Lypla1  18777   4844962 4845015 18777-exon-9  
1   Rgs20   58175   4910473 4910661 58175-exon-1  
1   Rgs20   58175   4912313 4912547 58175-exon-2  
1   Rgs20   58175   4916896 4916979 58175-exon-3  

最佳答案

一行:

awk  'FNR==1{print $0,"exon_number";next}p!=$3{c=0;p=$3}{print $0, $3"-exon-"++c}' infile

说明:

 awk  'FNR==1{                             # If first line read by awk
           print $0,"exon_number";         # print current record, 
                                           # and other header for new field
           next                            # we are done go to next line
       }
       p!=$3{                              # if p is not equal to 3rd column
           c=0;                            # reset counter variable
           p=$3                            # set variable p with 3rd column value                                   
                                           # Here you assume p mean previous value
       }
       {
          print $0, $3"-exon-"++c          # print current record, 
                                           # 3rd field 
                                           # "-exon-" string and
                                           # pre-increment variable c
       }
      ' infile

关于awk - 打印行号(如 NR),但为 $3 中的每个新字段变量重新编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079520/

相关文章:

linux - 根据linux中的文件名更改文件中的某个数字

linux - 使用 Awk 外部定义的变量

linux - awk 中的搜索模式

linux - 使用来自 Traceroute 输出的 shell 脚本从文件中提取并查找最小值、最大值和平均值的脚本

linux - 狂欢 : Search Contents of File A in File B and Print lines of File A in File C

awk - 当行 ID 匹配时,如果子字符串中存在另一个文件中的两个字符位置,则从文件中提取子字符串

shell - 使用 awk 记录给定文件中每个单词出现的行

bash - 适用于 awk v4.0.2 但不适用于 >= 4.2.1 的 awk 表达式

awk - 如何在awk中为每个循环执行命令?

python - 无法通过 AWK/Python 使每个句子从 LaTex 中的新行开始