将正则表达式结果写入新文件

时间:2015-05-21 09:07:30

标签: ruby regex stdout

我有一个设备列表:

  • IPC-bei640-R-BR-01
  • IPC-bei640-R-BR-02
  • IPC-bei640-R-BR-03
  • IPC-bei640-R-BR-04
  • IPC-bei640-R-BR-05
  • IPC-bem640-R-BR-01
  • IPC-bem640-R-BR-02
  • IPC-bem640-R-BR-03
  • IPC-crg660-R-BR-02
  • IPC-geb680-R-BR-04
  • IPC-lgv630-R-BR-01

这个小小的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" ]

我正试图以这种格式获得所有结果:

  • bei640-01
  • bei640-02
  • bei640-03
  • bei640-04

2 个答案:

答案 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"]