相当于awk的RS,NF和OFS的Ruby单行代码是什么?

时间:2019-01-31 06:51:35

标签: ruby awk

我有这个文件:

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等同于集合RS="\n\n+"

但是我想使用Ruby一线执行此操作。我想出了这个:

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的{​​{1}},awkRS等效的NF吗?
谢谢:)

1 个答案:

答案 0 :(得分:3)

$ 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排行记录分隔符