繁体   English   中英

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

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

基本上这就是问题所在。 我试图弄清楚如何将“卡片排序”一词替换为“卡片排序”,因为两个词之间的空格弄乱了我拥有的另一个脚本。 我需要将新的字符串替换(CardSort)写在文件上,并用空格替换以前的字符串。

我整天都在努力(关于编程:(),我真是个笨蛋,这是到目前为止我要提出的内容:

# 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

我认为问题在于我尚未定义变量“ file_name”,但我不知道应将其定义为什么。 基本上,它只需要遍历整个目录并进行更改即可。

另外,如果一个文件夹中有多个文件夹和子目录,那么如何使它们遍历所有文件夹并应用更改,而不必一个个地遍历每个文件夹? 感谢所有帮助人员,我真的很感激。

您不需要定义file_name就是块的结果。 如果您觉得什么都没发生,可能是因为您的表情什么也没返回。 尝试将puts file_name添加到块中,您将看到找到的文件。 我的猜测是您的脚本没有要迭代的文件,因为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