평평한 .txt 파일에 데이터 청크를 저장하는 스크립트를 작성하려고합니다. (파일 크기가 100 줄 미만)입니다.텍스트 파일에서 일치하는 한 줄을 어떻게 업데이트합니까?
어쨌든, 나는 그 라인의 새로운 값으로 하나의 매치 라인을 갱신하려고 노력하고 있지만, 그 라인의 모든 것을 홀로 남겨 두지 만, 그 라인을 대체하는 대신 단지 한 라인 만 수정하는 방법을 알 수는 없다. 전체 파일. textfile.txt
내용은 항상 형식으로 구성됩니다
# get file contents as array.
array_of_lines = File.open("textfile.txt", "r").readlines.map(&:chomp)
line_start = "123456:" # unique identifier
new_string = "somestring" # a new string to be put after the line_start indentifier.
# cycle through array finding the one to be updated/replaced with a new line.
# the line we're looking for is in format 123456:some old value
# delete the line matching the line_start key
array_of_lines.delete_if(|line| line_start =~ line)
# write new string into the array.
array_of_lines.push("#{line_start}:#{new_string}")
# write array contents back to file, replacing all previous content in the process
File.open("textfile.txt", "w") do |f|
array_of_lines.each do |line|
f.puts line
end
end
:
이UNIQUE_ID : string_of_text
나는 unique_id
을 일치시킬 수 있습니다 여기에
내가하는 일을하는 더 좋은 방법이 있습니까?
전체 파일을 메모리로 읽어 들여 모든 파일을 반복하여 파일의 한 줄만 업데이트하면 약간 비효율적 인 것처럼 보입니다.
참고 사항 : http://stackoverflow.com/questions/4397412/read-edit-and-write-a-text-file-line-wise-using-ruby/4399299#4399299 –
감사합니다 웨인, 알아두면 좋음 잠재적 인 성능/메모리 문제에 대해 – Jannis
파일을 메모리에 저장하지 않는다면'readlines'를 사용하지 마십시오. 스크립트의 사용 가능한 메모리보다 크면 처리가 크롤링됩니다. 대신'foreach' 또는'each_line'을 사용하여 파일을 줄 단위로 읽으십시오. 더 빠르고 확장 성이 뛰어납니다. http://stackoverflow.com/a/25189286/128421 –