Edit Each Line in a File in Ruby

Edit each line in a file in Ruby

The one of the better solutions(and safest) is to create a temporary file using TempFile, and move it to the original location(using FileUtils) once you are done:

   require 'fileutils'
require 'tempfile'

t_file = Tempfile.new('filename_temp.txt')
File.open("filename.txt", 'r') do |f|
f.each_line{|line| t_file.puts line.split(",")[0].to_s }
end
t_file.close
FileUtils.mv(t_file.path, "filename.txt")

How to edit every x amount of lines in txtfile in Ruby?

You can use modulus division as below where n refers to the nth line you want to process and i refers to the 0-based index for the file lines. Using those two values, modulo math provides the remainder from integer division which will be 0 whenever the 1-based index (i+1) is multiple of n.

n = 3 # modify every 3rd line

File.open('edit_fr.txt','w') do |f| # Open the output file
File.open('fr.txt').each_with_index do |line,i| # Open the input file
if (i+1) % n == 0 # Every nth line
f.print line.chomp # Remove newline
else # Every non-nth line
f.puts line # Print line
end
end
end

More info is available on Wikipedia: http://en.wikipedia.org/wiki/Modulo_operation

In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).

Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division of a by n. For instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3. (Note that doing the division with a calculator will not show the result referred to here by this operation; the quotient will be expressed as a decimal fraction.)

Replace line in text file with a new line

First, open the file and save the actual content. Then, replace the string and write the full content back to file.

def remove_line(string)
# save the content of the file
file = File.read('test.txt')
# replace (globally) the search string with the new string
new_content = file.gsub(string, 'removed succesfully')
# open the file again and write the new content to it
File.open('test.txt', 'w') { |line| line.puts new_content }
end

Or, instead of replacing globally:

def remove_line(string)
file = File.read('test.txt')
new_content = file.split("\n")
new_content = new_content.map { |word| word == string ? 'removed succesfully' : word }.join("\n")
File.open('test.txt', 'w') { |line| line.puts new_content }
end

Replace a specific line in a file using Ruby

How about something like:

lines = File.readlines('file')
lines[2] = 'close' << $/
File.open('file', 'w') { |f| f.write(lines.join) }

Replace a line from a text file

Let's analyze what's going wrong here. File#any? returns true or false, according as its block returns true for at least one of the block arguments passed. You are not returning true or false from the block and you have no interest in the question of whether the result of File#any? is true or false. So this is clearly the wrong method.

Moreover, as you rightly say, you are writing a new (added) line, not in any way replacing the existing line.

What you want to do is cycle through the file line by line, reading each line, and:

  • If the line doesn't contain the target string, write the very same line

  • If the line does contain the target string, write the substituted line

Thus you will read the whole file and write the whole file (with or without the substitution) in its place. This approach actually involves two files, since you have already read the line before the time comes to write it.

Alternatively you could just read the whole file at once, split it into lines, look for the target and perform the substitution, join back into a single string, and write it. If the files are small (so that the strings are small), this is much the simplest way.

For the correct patterns, see https://stackoverflow.com/a/4399299/341994

Ruby - read each line in file to object and add object to array

If I have understood you correctly, this should work:

class Solution 
attr_reader :analyzers

def initialize()
@analyzers = []
end

def analyze_file()
count = 0;
File.open('test.txt').each_line do |line|
la = LineAnalyzer.new(line, count)
@analyzers.push la
count += 1
end
end
end

Little digressing from question, please note that - at most places in ruby you don't need ;. Ruby is good so it doesn't complain about it, but its good to stay with the standard conventions.

edit first line of multiple files in place with a ruby one-liner

This code will work:

ruby -pi -e 'sub(/^/,"New line goes at top\n") if $FILENAME != $F;$F = $FILENAME' file*

Delete first two lines and add two lines to file

I'd start with something like this:

NEWLINES = {
0 => "New Title",
1 => "\nfff"
}

File.open('test.txt.new', 'w') do |fo|
File.foreach('test.txt').with_index do |li, ln|
fo.puts (NEWLINES[ln] || li)
end
end

Here's the contents of test.txt.new after running:

New Title

fff
aaa
bbb
ccc

The idea is to provide a list of replacement lines in the NEWLINES hash. As each line is read from the original file the line number is checked in the hash, and if the line exists then the corresponding value is used, otherwise the original line is used.

If you want to read the entire file then substitute, it reduces the code a little, but the code will have scalability issues:

NEWLINES = [
"New Title",
"",
"fff"
]

file = File.readlines('test.txt')
File.open('test.txt.new', 'w') do |fo|
fo.puts NEWLINES
fo.puts file[(NEWLINES.size - 1) .. -1]
end

It's not very smart but it'll work for simple replacements.

If you really want to do it right, learn how diff works, create a diff file, then let it do the heavy lifting, as it's designed for this sort of task, runs extremely fast, and is used millions of times every day on *nix systems around the world.



Related Topics



Leave a reply



Submit