##When I have to insert numbers that are omitted between numbers###
##For example, the file contents are as follows.
00:data
04:data
05:data
06:data
07:data
08:data
09:data
10:data
13:data
14:data
15:data
16:data
19:data
I need to insert 01,02,03 between 00 and 04. And I also need to insert 11,12.
On linux box, I may have to use awk sed or perl. But for me ruby is much easier.
The code is as follows.
[root@redhat2 ~]# cat t.rb
#!/usr/bin/env ruby
#Function to less than 9 insert method differently
def more_than_9(a,n)
if n < 9
a.insert(n,"0#{n}:data")
else
a.insert(n,"#{n}:data")
end
end
#File open and into array
a=File.new("./test.csv").read.split("\n")
s=a.size
i=0
while i < (s-1)
if (a[i+1].split(":")[0].to_i - a[i].split(":")[0].to_i) > 1
nx=a[i+1].split(":")[0].to_i
while i+1 < nx
n=i+1
more_than_9(a,n)
i=n
end
end
i=i+1
end
#Puts results
puts a
#So, the result of executing this script is as follows.
[root@redhat2 ~]# ruby t.rb
00:data
01:data
02:data
03:data
04:data
05:data
06:data
07:data
08:data
09:data
10:data
11:data
12:data
13:data
14:data
15:data
16:data
19:data
# #################################3
No comments:
Post a Comment