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 =”.tmp”, ‘a+’)
IO.foreach(file_name) do |line|
value = yield(line)
temp.puts yield(line) if value
mv file_name+’.tmp’, file_name

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

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

#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? }

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

Leave a Reply

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

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

Facebook photo

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

Connecting to %s