简体   繁体   中英

How to search and replace strings in all of the files in my directory using Ruby?

Basically here's the issue. I am trying to figure out how to replace the word "Card Sort" to "CardSort" instead because the space between the two words is messing up another script that I have. I need the new string replacement (CardSort) to be written in on the file and replace the previous string with a space in it.

I've been working on this all day (I'm pretty nooby when it comes to programming :( ) and this is what I've come up with so far:

# Set the variables for find/replace
@original_string_or_regex = /Card Sort/
@replacement_string = "CardSort"

Dir.foreach("~/Desktop/macshapa_v2") do |file_name|
    next if file_name == '.' or file_name == '..'  # do work on real items
    text = File.read(file_name)
    replace = text.gsub!(@original_string_or_regex, @replacement_string)
    File.open(file_name, "w") { |file| file.puts replace }
end

I think the problem lies with the fact that I have not defined the variable "file_name" but I don't know what it should be defined as. Basically, it just needs to run through the entire directory, making the changes it needs to make.

Additionally, if I had multiple folders and subdirectories in a folder, how could I make it run through all of them and apply the changes without having to go through each folder one by one? Thanks for all the help guys I truly appreciate it.

You do not need to define file_name it is the result of the block. If you feel like nothing happens, it is probably because your expression returned nothing. Try adding puts file_name inside the block and you will see which files it found. My guess is that your script had no file to iterate on because Dir.foreach will not work with ~/ .

# Set the variables for find/replace
# you can use regular variables here
original_string_or_regex = /Card Sort/
replacement_string = "CardSort"

# Dir.glob will take care of the recursivity for you
# do not use ~ but rather Dir.home
Dir.glob("#{Dir.home}/Desktop/macshapa_v2/*") do |file_name|
  text = File.read(file_name)
  replace = text.gsub!(original_string_or_regex, replacement_string)
  File.open(file_name, "w") { |file| file.puts replace }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM