【问题标题】:Print columns in a reoccurring pattern with awk使用 awk 以重复出现的模式打印列
【发布时间】:2013-03-05 11:37:24
【问题描述】:

我有相当宽的文件,其中包含制表符分隔的列:

Donna   25.07.83   Type1   A   B   C   D  E   F   G   H  ....
Adam    17.05.78   Type2   A   B   C   D  E   F   G   H  ....

我想打印出所有内容,但是在第三列之后每两列打印一个选项卡..

Donna   25.07.83   Type1   AB   CD  EF   GH  ....
Adam    17.05.78   Type2   AB   CD  EF   GH  ....

我认为可能有比

更聪明的方法来做到这一点
awk '{OFS="\t"} {print $1, $2, $3, $4$5, $6$7, $8$9}' 

等等,特别是因为我的文件中有超过 1000 列。 awk 可以这样做吗?

【问题讨论】:

    标签: awk


    【解决方案1】:
    awk '{for(i=1;i<=NF;i++){if(i>=4){$i=$i$(i+1);$(i+1)="";i+=1}}print}' your_file
    

    测试:

    > cat temp
    Donna   25.07.83   Type1   A   B   C   D  E   F   G   H
    Adam    17.05.78   Type2   A   B   C   D  E   F   G   H
    > awk '{for(i=1;i<=NF;i++){if(i>=4){$i=$i$(i+1);$(i+1)="";i+=1}}print}' temp
    Donna 25.07.83 Type1 AB  CD  EF  GH 
    Adam 17.05.78 Type2 AB  CD  EF  GH 
    

    【讨论】:

    • 谢谢,我明天用。请问NF部分是什么以及迭代的位?
    【解决方案2】:

    很恶心,但有效:

    awk '{printf "%s\t%s\t%s",$1,$2,$3; for(i=4;i<=NF;i+=2) printf "\t%s%s",$i,$(i+1); print ""}' wide.txt
    

    NF 是一个 awk 变量,它的值是一个数字,告诉你有多少 当前行具有的列。您可以在手册中找到它。

    让我们把它拆开:

    #!/usr/bin/awk -f
    
    { 
      printf "%s\t%s\t\%", $1, $2, $3;  # print the first 3 columns, explicitly 
                                        # separated by TAB. No NEWLINE will be printed.
    
      # We want to print the remaining columns in pairs of $4$5, $6$7
    
      for( i = 4; i <= NF ; i+=2 )       # i is 4, then 6, then 8 ... till NF (the num. of the final column)
         printf "\t%s%s", $i, $(i+1);   # print \t$4$5, then \t$6$7, then \t$8$9 
    
      print ""                          # We haven't print the end-of-line NEWLINE
                                        # yet, so this empty print should do it.
    }
    

    【讨论】:

    • 谢谢,我觉得这有点难以理解,但我可以看到 "%s\t%s\t%s" 位属于 printf 并且可能用于打印选项卡。我可能不得不像上面一样查看 awk 文档中的 NF,但我没有完全遵循。谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    相关资源
    最近更新 更多