简体   繁体   English

如何使用Ruby搜索和替换目录中所有文件中的字符串?

[英]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. 我需要将新的字符串替换(CardSort)写在文件上,并用空格替换以前的字符串。

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. 我认为问题在于我尚未定义变量“ file_name”,但我不知道应将其定义为什么。 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. 您不需要定义file_name就是块的结果。 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. 尝试将puts file_name添加到块中,您将看到找到的文件。 My guess is that your script had no file to iterate on because Dir.foreach will not work with ~/ . 我的猜测是您的脚本没有要迭代的文件,因为Dir.foreach无法与~/

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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