2014-11-14 52 views
0

我是Ruby的新手,我試圖用RegEx做多個搜索並替換輸入文本文件,但是我的代碼不工作,我想我明白爲什麼它不會沒有工作,但我不知道我需要的語法來使它工作。 赫雷什我的代碼:在一個文件中搜索和替換

# encoding: utf-8 
#!/usr/bin/ruby 

# open file to read and write 
file = File.open("input.txt", "r+") 
# get the contents of the file 
contents = file.read 
file.close 

reassign = contents.gsub(/\w+/, '£££££') 

# save it out as a new file 
new_file = File.new("output.txt") 
new_file.write(reassign) 
new_file.close 

這是錯誤消息:

C:/Users/parsonsr/RubymineProjects/Test 3/test3.rb:14:in `write': not opened for writing (IOError) 
    from C:/Users/parsonsr/RubymineProjects/Test 3/test3.rb:14:in `<top (required)>' 
    from -e:1:in `load' 
    from -e:1:in `<main>' 

我試圖使用陣列通過每個線和改變什麼相關但隨後只保存陣列到什麼在輸出不是文件的其餘部分。 我需要它來改變已經存在於一個文件中的文本,或者改變文本,然後將新的更改保存到輸出文件中,以最簡單的方式保存。 希望這是有道理的。 謝謝

回答

0

看看documentation。請注意,文件#打開默認情況下接收模式「r」。 所以答案是:改變

File.new("output.txt") 

File.new("output.txt", "w") 

你可以在Ruby中做的另一件事是:

File.write("output.txt", reassign) 

或者:

File.open("output.txt", "w") 

而且,我不知道什麼是p但是考慮一個大文件,您可能需要讀取批處理行並將它們每次寫入輸出文件,而不是一次全部讀取到內存中。

+0

非常感謝,它的工作完美! – Rebs 2014-11-17 09:53:30