Ruby的一行程序与awk的RS、NF和OFS的等价性是什么?

ekqde3dh  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(85)

我有这个文件:

1
2
3
4

a
b
c

XY
Z

字符串
我想将每个块转换为TAB分隔行,并将当前timestamp附加在最后一列,以获得如下输出:
我可以使用awk来这样做:

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


其中空RS等同于set 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是否与awkRSNFOFS等价?

8wigbo56

8wigbo561#

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

相关问题