4

Ruby初心者はこちら!

Ruby の File.open メソッドには、r、w、a、r+、w+、a+ および補数の b などの特定のモードがあることを認識しています。r、w、および a モードの使用を完全に理解しています。しかし、「+」記号の付いたものの使い方が理解できないようです。例とその使用方法の説明があるリンクを誰か教えてもらえますか?

行を読み取って、同じ量のコンテンツでその場で編集/置換するために使用できますか? もしそうなら、どうやって?

サンプルデータファイル: a.txt

aaa
bbb
ccc
ddd

デモ.rb

file = File.open "a.txt","r+"
file.each do |line|
  line = line.chomp
  if(line=="bbb")then
  file.puts "big"
  end
end
file.close

「bbb」を「big」に置き換えようとしていますが、これを取得しています:-メモ帳++で

aaa
bbb
big

ddd

メモ帳で

aaa
bbb
bigddd
4

2 に答える 2

11

このドキュメントを別の回答から奪ったので、私のものではなく、解決策は私のものです

r  Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. 
r+ Read-write mode. The file pointer will be at the beginning of the file. 
w  Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. 
w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a  Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. 
a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

編集: ここでサンプルの解決策を示します。ほとんどの場合、文字列全体が gsubbed されてファイルに書き戻されますが、ファイル全体を書き換えずに「infile」を置き換えることも可能です。同じ長さの文字列に置き換えるには注意が必要です。 .

File.open('a.txt', 'r+') do |file|
  file.each_line do |line|
    if (line=~/bbb/)
      file.seek(-line.length-3, IO::SEEK_CUR)
      file.write 'big'
    end
  end
end 

=>
aaa
big
ccc
ddd

そして、これはより従来の方法ですが、他のほとんどのソリューションよりも簡潔です

File.open(filename = "a.txt", "r+") { |file| file << File.read(filename).gsub(/bbb/,"big") } 

EDIT2:これはさらに短くできることに気づきました

File.write(f = "a.txt", File.read(f).gsub(/bbb/,"big"))
于 2012-04-16T11:18:46.873 に答える
0

したがって、ファイル全体を変数に読み込んでから、置換を実行し、変数の内容をファイルに書き戻します。私は正しいですか?私はちょっとインラインのものを探していました

それがやり方です。IO#readlinesまたは、すべての行を読み込んで処理するために使用することもできArrayます。

そして、これはすでに答えられています:

ファイル テキストのパターンを検索し、指定された値に置き換える方法

パフォーマンスやメモリ使用量が気になる場合は、適切なツールを適切なジョブに使用してください。オン*nix(または Windows の cygwin):

sed -i -e "s/bbb/big/g" a.txt

あなたが望むことを正確に行います。

于 2012-04-16T13:47:26.160 に答える