我有这个文件:
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}},awk
和RS
等效的NF
吗?
谢谢:)
答案 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
排行记录分隔符