【问题标题】:Reformatting text file using awk and cut as a one liner使用 awk 重新格式化文本文件并将其剪切为单行
【发布时间】:2021-02-25 11:14:21
【问题描述】:

数据:

CHR SNP BP A1 TEST NMISS BETA SE L95 U95 STAT P 
1   chr1:1243:A:T 1243 T ADD 16283 -6.124 0.543 -1.431 0.3534 -1.123 0.14

期望的输出:

MarkerName P-Value 
  chr1:1243  0.14

实际文件是1.2G的像上面那样的行

我需要将文本的第二列去掉第二个冒号,然后将其粘贴到最后的第 12 列并给它一个新的标题。

我试过了:

awk '{print $2, $12}' | cut -d: -f1-2

但这会删除冒号后的整行,我想保留“p”列

我将其输出到一个新文件,然后使用 awk 将其粘贴到 P 值列上,但想知道是否有一种单行方法可以做到这一点?

非常感谢

【问题讨论】:

  • 使用split($2,a,/:/)和printf "%s:%s %s\n",a[1],a[2],$12。
  • 我在下面实现了我的评论作为答案。

标签: bash awk text cut


【解决方案1】:

我的评论更易于理解:

$ awk '
BEGIN {
    print "MarkerName P-Value"          # output header
}
NR>1 {                                  # skip the funky first record
    split($2,a,/:/)                     # split by :
    printf "%s:%s %s\n",a[1],a[2],$12   # printf allows easier output formating
}' file

输出:

MarkerName P-Value
chr1:1243 0.14

【讨论】:

  • 非常感谢!不知道灵魂教父是个 awk 爱好者!
【解决方案2】:

编辑:在这里再添加一个解决方案,因为 OP 提到我的第一个解决方案不知何故不适用于 OP,但它对我来说很好,作为替代添加这个在这里。

awk '
BEGIN{
  print "MarkerName P-Value"
}
FNR>1{
  match($2,/([^:]*:){2}/)
  print OFS substr($2,RSTART,RLENGTH-1),$NF
}
' Input_file


使用显示的示例,您能否尝试以下操作。您无需将cut 与awk 一起使用,awk 可以自己处理所有事情。

awk -F' +|:' '
BEGIN{
  print "MarkerName P-Value"
}
FNR>1{
  print OFS $2":"$3,$NF
}
' Input_file

说明:为上述添加详细说明。

awk -F' +|:' '                 ##Starting awk program from here and setting field separator as spaces or colon for all lines.
BEGIN{                         ##Starting BEGIN section of this program from here.
  print "MarkerName P-Value"   ##Printing headers here.
}
FNR>1{                         ##Checking condition if line number is greater than 1 then do following.
  print OFS $2":"$3,$NF        ##Printing space(OFS) 2nd field colon 3rd field and last field as per OP request.
}
' Input_file                   ##Mentioning Input_file name here.

【讨论】:

    【解决方案3】:
    $ awk -F'[: ]+' '{print (NR==1 ? "MarkerName P-Value" : $2":"$3" "$NF)}' file
    MarkerName P-Value
    chr1:1243 0.14
    

    【讨论】:

      【解决方案4】:

      Sed 替代方案:

      sed -En '1{s/^.*$/MarkerName\tP-Value/p};s/([[:digit:]]+[[:space:]]+)([[:alnum:]]+:[[:digit:]]+)(.*)([[:digit:]]+\.[[:digit:]]+$)/\2\t\4/p'
      

      对于第一行,用整行替换标题。然后,根据正则表达式将该行分成 4 个部分,然后打印第 2 个小节,然后是一个制表符,然后是第 4 个小节。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-06
        • 2020-05-29
        • 2020-06-18
        • 2020-07-19
        • 2015-11-09
        相关资源
        最近更新 更多