开发者

Remove strings begining with 'AUTO_INCREMENT=' in 2 files

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 b开发者_JAVA技巧e removed from both files. Thanks for any help or input as I am new to ruby and decided to give it a try.


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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜