Follow up to the Use Ruby to Prefix all lines /Postfix all lines/Remove empty lines/Replace strings in all lines of a file

In my previous post, I showed a ruby program that can help you iterate over lines of a file and make changes to the file, here I rewritten the code in a much more ruby-way, where I am using code blocks and iterators take a look
module DevFileutils
include FileUtils::Verbose

# Open file, iterate through each line and yield on each line, take results of yield
def each_line_of_file file_name
temp = File.new(file_name+”.tmp”, ‘a+’)
IO.foreach(file_name) do |line|
value = yield(line)
temp.puts yield(line) if value
end
temp.close
mv file_name+’.tmp’, file_name
end

# Opens a file and adds prefix to each line
def prefix  file_name, prefix
each_line_of_file(file_name) { |line| prefix + line }
end

# Opens a file and adds postfix to each line
def postfix file_name, postfix
each_line_of_file(file_name) { |line| line.chomp + postfix }
end

#removes all empty lines from a file
def remove_empty_lines file_name
each_line_of_file(file_name) { |line| line if !line.chomp.empty? }
end

def replace file_name,string,with_string
each_line_of_file(file_name) { |line| line.gsub(string,with_string) }
end
end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s