ruby - 如何在 Ruby 中编辑 txtfile 中的每 x 行?

标签 ruby

我正在尝试使用 Ruby 更改文本文件中每隔一行的内容(有些文本文件我需要每三行更改一次,依此类推。)

我找到了 this question有助于遍历每一行,但我特别需要帮助每 x 行进行更改。

### 是我遇到问题的部分(迭代 x 行数。)

text = File.open('fr.txt').read
clean = ### .sub("\n", " ");
new = File.new("edit_fr.txt", "w")
new.puts clean
new.close

最佳答案

您可以如下使用模除法,其中 n 指的是您要处理的第 n 行,i 指的是文件行的从 0 开始的索引。使用这两个值,模数学提供整数除法的余数,只要基于 1 的索引 (i+1) 是 n 的倍数,余数将为 0。

n = 3 # modify every 3rd line

File.open('edit_fr.txt','w') do |f|               # Open the output file
  File.open('fr.txt').each_with_index do |line,i| # Open the input file
    if (i+1) % n == 0                             # Every nth line
      f.print line.chomp                          # Remove newline
    else                                          # Every non-nth line
      f.puts line                                 # Print line
    end
  end
end

更多信息可在维基百科上找到:http://en.wikipedia.org/wiki/Modulo_operation

In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).

Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division of a by n. For instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3. (Note that doing the division with a calculator will not show the result referred to here by this operation; the quotient will be expressed as a decimal fraction.)

关于ruby - 如何在 Ruby 中编辑 txtfile 中的每 x 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292867/

相关文章:

ruby - IRB 和脚本中的 TOPLEVEL_BINDING 区别

ruby-on-rails - Rails 的最佳图像优化技术

javascript - Dashing 未检测到 coffeescript 的更改

Ruby - 带索引的数组

ruby - 如何计算和检查传递的参数?

ruby-on-rails - 启动 Rails 时定义 "current time"?

mysql - mysql 是否有更改数据库的限制?

javascript - Sencha touch 应用程序加载器一直闪烁

Ruby 企业版 + OpenSSL -> "certificate verify failed"

ruby - 获取 Ruby 中 gsub 替换的数量