在ruby中解析位置文件 [英] parsing position files in ruby
问题描述
我有一个示例位置文件,如下所示.
I have a sample position file like below.
789754654 COLORA SOMETHING1 19370119FYY076 2342423234SS323423
742784897 COLORB SOMETHING2 20060722FYY076 2342342342SDFSD3423
我对职位54-61(第四栏)感兴趣.我想将日期更改为其他格式.因此最终结果将是:
I am interested in positions 54-61 (4th column). I want to change the date to be a different format. So final outcome will be:
789754654 COLORA SOMETHING1 01191937FYY076 2342423234SS323423
742784897 COLORB SOMETHING2 07222006FYY076 2342342342SDFSD3423
这些列用空格而不是制表符分隔.最终文件应具有与原始文件相同的空格数....唯一更改的地方应该是日期格式.我怎样才能做到这一点?我写了一个脚本,但是它将丢失原始空间,并且位置会混乱.
The columns are seperated by spaces not tabs. And the final file should have exact number of spaces as the original file....only thing changing should be the date format. How can I do this? I wrote a script but it will lose the original spaces and positioning will be messed up.
file.each_line do |line|
dob = line.split(" ")
puts dob[3] #got the date. change its format
5.times { puts "**" }
end
任何人都可以提出更好的策略,以使原始文件中的位置保持不变吗?
Can anyone suggest a better strategy so that positioning in the original file remains the same?
推荐答案
您可以使用line [range]替换部分行,其余部分保持不变.
You can use line[range] to replace part of a line, leaving the rest the same.
#!/usr/bin/ruby1.8
line = "789754654 COLORA SOMETHING1 19370119FYY076 2342423234SS323423"
line[44..57] = "01191937FYY076"
p line
# => "789754654 COLORA SOMETHING1 01191937FYY076 2342423234SS323423"
这篇关于在ruby中解析位置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!