【问题标题】:How to print every 4th column up to nth column and from (n+1)th column to last using awk?如何使用awk打印每第4列到第n列以及从第(n + 1)列到最后一列?
【发布时间】:2011-03-02 15:10:03
【问题描述】:

我有一个由空格分隔的 119 列的数据集,我喜欢选择列 (3,7,11,...,47,51), (52,53,54,...,118,119) 并打印他们出到另一个文件。如何使用 awk 做到这一点?

Input file 

c1 c2 c3...c119

Output file

c3 c7 c11 ... c51 c52 c53 c54 ... c118 c119 

感谢您的帮助

【问题讨论】:

    标签: awk


    【解决方案1】:
    awk '{for(i=3;i<=51;i+=4) printf "%s ",$i ;for(i=52;i<=119;i++) {printf "%s ",$i} ;print ""}' file
    

    【讨论】:

    • 是为每个输入记录打印一个输出记录,还是为每列打印一个记录?
    • 它将按列打印。
    • 似乎 OP 需要由一行中的所有列组成的输出文件(我猜)
    【解决方案2】:
    {a=""; 
     for (i=0 ;i<=12; i++) {a = a  $(3+4 * i) " "};
     for (i=52 ;i<=119; i++) {a = a  $(i) " "};
     print a}  
    

    HTH!

    【讨论】:

      【解决方案3】:

      这就是你要找的吗?

      awk '{s=""; for (i = 3; i <= 51; i+=4) {s = s $i " "}; for (i = 52; i <= 119; i++) {s = s $i " "}; print s}' inputfile
      

      【讨论】:

      • 看来你需要为下一条记录清空变量s
      【解决方案4】:
      awk 'for(i=3;i<=119;i+a) 
           {
           if (i<52)
           {
           printf "%s ",$i};
           a=4;
           }
           else
           {
           printf "%s ",$i};
           a=1;
           }
           }' file
      

      【讨论】:

        猜你喜欢
        • 2023-02-04
        • 1970-01-01
        • 2011-02-27
        • 2017-04-23
        • 1970-01-01
        • 2015-11-04
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多