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

For some reason or the other I had to do bulk operations on files, like prefix/postfix all lines or remove empty lines
, yeah I could do it with some unix command, but I am already using ruby to massage the data just wanted to extand that.So here
is what I did wrote a ruby script to do it now I can do stuff like

prefix ( ‘c:\tmp\zip.txt’,’some-prefix’ )

The script, hmmm I wonder if I could submit this to ruby people.

require 'fileutils'

module DevFileutils
include FileUtils::Verbose

# Opens a file and adds prefix to each line
def prefix file_name, prefix
temp = File.new(file_name+".tmp", 'a+')
IO.foreach(file_name) do |line|
temp.puts prefix + line
end
temp.close
mv file_name+'.tmp', file_name
end

# Opens a file and adds postfix to each line
def postfix file_name, postfix
temp = File.new(file_name+".tmp", 'a+')
IO.foreach(file_name) do |line|
temp.puts line.chomp + postfix
end
temp.close
mv file_name+'.tmp', file_name
end

#removes all empty lines from a file
def remove_empty_lines file_name
temp = File.new(file_name+".tmp", 'a+')
IO.foreach(file_name) do |line|
temp.puts line if !line.chomp.empty?
end
temp.close
mv file_name+'.tmp', file_name
end

def replace file_name,string,with_string
temp = File.new(file_name+".tmp", 'a+')
IO.foreach(file_name) do |line|
temp.puts line.gsub(string,with_string)
end
temp.close
mv file_name+'.tmp', file_name
end
end

Advertisements

7 thoughts on “Use Ruby to Prefix all lines /Postfix all lines/Remove empty lines/Replace strings in all lines of a file

  1. Rong Ou

    prefix:
    sed ‘s/^.*$/prefix(&)/’ outputfile

    suffix:
    sed ‘s/^.*$/(&)suffix/’ outputfile

    remove blank lines:
    sed ‘/^$/ d’ outputfile

    replace strings:
    sed ‘s/old/new/’ outputfile

  2. Rong Ou

    Damn, it ate all my redirects. Here is it again:

    prefix:
    sed ’s/^.*$/prefix(&)/’ < inputfile > outputfile

    suffix:
    sed ’s/^.*$/(&)suffix/’ < inputfile > outputfile

    remove blank lines:
    sed ‘/^$/ d’ < inputfile > outputfile

    replace strings:
    sed ’s/old/new/’ < inputfile > outputfile

  3. pity 2014 ips

    Someone necessarily assist to make critically posts I’d state. This is the first time I frequented your website page and so far? I amazed with the analysis you made to make this particular publish extraordinary. Fantastic process!

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