0

I am trying to create a ruby script that loads 2 .sql files and removes all strings that begin with 'AUTO_INCREMENT=' There are multiple occurrences of this in my .sql files and all I want is them to be removed from both files. Thanks for any help or input as I am new to ruby and decided to give it a try.

andrew
  • 3
  • 1

3 Answers3

0

Have you tried using Regex for this? If you want to remove the whole line, you could simply match ^AUTO_INCREMENT=.+$ and replace it with an empty string. That pattern should match an entire line beginning with AUTO_INCREMENT.

Here's a good site to learn Regex if you aren't familiar with it:

Hope that works for you.

Justin Self
  • 6,137
  • 3
  • 33
  • 48
0

You should read up on IO, String, Array for more details on methods you can use.

Here's how you might read, modify, and save the contents of one file:

# Opens a file for reading.
file = File.open("file1.txt")

# Reads all the contents into the string 'contents'.
contents = file.read
file.close

# Splits contents into an array of strings, one for each line.
lines = contents.split("\n")

# Delete any lines that start with AUTO_INCREMENT=
lines.reject! { |line| line =~ /^AUTO_INCREMENT=/ }

# Join the lines together into one string again.
new_contents = lines.join("\n")

# Open file for writing.
file = File.open("file1.txt", "w")

# Save new contents.
file.write(new_contents)
file.close
mjwhitt
  • 63
  • 4
0

Given the right regexp (the one below might not be the most correct given the syntax), and the answer given there to a similar question, it is rather straightforward to put a script together:

file_names = ['file1.sql', 'file2.sql']

file_names.each do |file_name|
  text = File.read(file_name)
  File.open(file_name, 'wb') do 
    |file| 
    file.write(text.gsub(/\s*AUTO_INCREMENT\s*(\=\s*[0-9]+)?/, "")) 
  end
end
Community
  • 1
  • 1
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80