代码之家  ›  专栏  ›  技术社区  ›  Tyl

RubyOne班轮相当于awk的rs、nf和ofs是什么?

  •  3
  • Tyl  · 技术社区  · 6 年前

    我有这个文件:

    1
    2
    3
    4
    
    
    a
    b
    c
    
    XY
    Z
    

    我想把每个块转换成 TAB 分隔行,并附加当前 timestamp 在最后一列中获取这样的输出:

    1   2   3   4   1548915098
    a   b   c   1548915098
    XY  Z   1548915098
    

    我可以用 awk 这样做:

    awk '$(NF+1)=systime()' RS= OFS="\t" file
    

    哪里空 RS 等于set RS="\n\n+" .

    但我想用RubyOne行程序来完成。我想到了这个:

    ruby -a -ne 'BEGIN{@lines=Array.new}; if ($_ !~ /^$/) then @lines.push($_.chomp) else (puts @lines.push(Time.now.to_i.to_s).join "\t"; @lines=Array.new) unless @lines.empty? end; END{puts @lines.push(Time.now.to_i.to_s).join "\t" unless @lines.empty?}' file
    

    这有点尴尬。

    有什么优雅的方法可以做到这一点吗?
    有没有 ruby 相当于 AWK 遥感 , NF OFS ?
    谢谢)

    1 回复  |  直到 6 年前
        1
  •  3
  •   Sundeep    6 年前
    $ awk '$(NF+1)=systime()' RS= OFS="\t" ip.txt
    1   2   3   4   1548917728
    a   b   c   1548917728
    XY  Z   1548917728
    
    $ # .to_s can be ignored here, since puts will take care of it
    $ ruby -00 -lane '$F.append(Time.now.to_i.to_s); puts $F.join("\t")' ip.txt
    1   2   3   4   1548917730
    a   b   c   1548917730
    XY  Z   1548917730
    
    • -00 段落模式
    • -a 自动拆分,结果来自 $F 数组
    • -l Chomps记录分隔符