我有这个文件:
1
2
3
4
a
b
c
XY
Z
我想将每个 block 转换为 TAB
分隔行,并在最后一列附加当前时间戳
以获得如下输出:
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
这有点尴尬。
有什么优雅的方法可以做到这一点吗?
是否存在与 awk
的 RS
、NF
和 OFS
等效的 ruby
>?
最佳答案
$ 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
删除记录分隔符
关于ruby - 与 awk 的 RS、NF 和 OFS 等价的 Ruby 单行代码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54454902/