Billy Logan Billy Logan - 6 months ago 18
Ruby Question

How to shift all lines to the right in Ruby text file?

Consider, I have a file with the following text:

create_table "users", force: :cascade do |t|
t.integer "age"
t.string "first_name"
t.string "last_name"
end


What would be a neat way to shift it to the right as if there was "\t" symbol before each line?

create_table "users", force: :cascade do |t|
t.integer "age"
t.string "first_name"
t.string "last_name"
end


My question has nothing to do with text editor. I'm asking how to shift text in file programmatically.

Answer

You can do that by processing the file line-by-line and writing to a new file. Try something like this:

spaces = 8
original_filename = 'outdented.txt'
new_filename = 'indented.txt'

File.open(new_filename, 'w') do |out_file|
  File.foreach(original_filename) do |line|
     out_file.puts "#{" "*spaces}#{line}"
  end
end

When run on this file (outdented.txt):

This file is not indented
Each line rests against the left margin
  Except this line
And that's all this file does

produces this output (indented.txt):

        This file is not indented
        Each line rests against the left margin
          Except this line
        And that's all this file does

If you like, you can remove the original file and rename the new file to the original filename:

File.delete(original_filename)
File.rename(new_filename, original_filename)

If you prefer tabs, you can choose replace the spaces variable with a tabs variable, and change the character to output:

tabs = 2
original_filename = 'outdented.txt'
new_filename = 'indented.txt'

File.open(new_filename, 'w') do |out_file|
  File.foreach(original_filename) do |line|
     out_file.puts "#{"\t"*tabs}#{line}"
  end
end
Comments