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
prefix:
sed ‘s/^.*$/prefix(&)/’ outputfile
suffix:
sed ‘s/^.*$/(&)suffix/’ outputfile
remove blank lines:
sed ‘/^$/ d’ outputfile
replace strings:
sed ‘s/old/new/’ outputfile
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
It’s very effortless to find out any topic on net as compared to books, as I found this article at this website.
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!
Awesome things here. I’m very glad to look your post. Thank you a lot and I’m taking a look forward to contact
you. Will you please drop me a e-mail?
What’s up Dear, are you really visiting this web page
on a regular basis, if so afterward you will absolutely obtain
nice know-how.|