Home > Programming, Ruby > Text file lines manipulation.

Text file lines manipulation.

A few simple little ruby scripts that will do some text file manipulation. If you couldn’t tell I was working on a project that required all these.

Convert all lines in a text file to lowercase (downcase) and save them in a new file, I could have saved them to the same file (see remove line number below) but I wanted to preserve the original file as well.

def fileToLower(inFile, outFile)
    File.open(outFile, 'a') do |fout|
        File.open(inFile) do |fin|
            fin.each_line do |line|
                fout.puts line.downcase
            end
        end
    end
end

Remove a specific line number from a text file.

def removeLine(fileName, lineNum)
    lines = File.readlines(fileName)
    count = 1
    File.open(fileName, "w") do |fout|
        lines.each do |line|
            fout.puts(line) unless count == lineNum
            count += 1
        end
    end
end

Get a single line from a text file.

def getSingleLine(fileName, lineNum)
   File.open(fileName) do |file|
      curLine = 1
      file.each_line do |line|
         return line if lineNum == curLine
         curLine += 1
      end
   end
end
Advertisements
Categories: Programming, Ruby
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: