我有一个设备列表:
这个小小的ruby脚本计算文件行braslist.txt用正则表达式扫描它并将结果写入名为“strippedfile.txt”的新文件
lines = IO.readlines("/usr/local/bin/braslist.txt")
# Linecount is forwarded to StdOut.
puts lines.length
str = File.read('braslist.txt')
file_name = ['strippedfile.txt']
file_name.each do |file_name|
text = File.read(file_name)
new_contents = str.scan(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/)
# open and write to a file with ruby
open('strippedfile.txt', 'w') { |f|
f.print new_contents
}
end
现在我似乎无法修复,在新文件“strippedfile”中,结果总是[“bei640”,“ - 01”] [“bei640”,“ - 02”] [“bei640”,“ - 03" ]
我正试图以这种格式获得所有结果:
答案 0 :(得分:1)
scan
会返回一系列匹配项,您可能需要join
它们:
- new_contents = str.scan(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/)
+ new_contents = str.scan(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/).map(&:join)
To print everything without quotes and brackets line by line:
- f.print new_contents
+ f.puts new_contents
答案 1 :(得分:1)
假设您的结果数组是
a = [["bei640", "-02"], ["bei640", "-03"]]
您可以使用join
来获得所需的结果
a.map{|i| i.join } #=> ["bei640-02", "bei640-03"]
或使用快捷方式mudasobwa
已解答
a.map(&:join) #=> ["bei640-02", "bei640-03"]