0

I'm trying to create a script in ruby that reads through the files in a folder, and merges them into an individual file.

This is what i've come up with

File.open('authorized_keys','a') do |mergedfile|
  @files = Dir.glob('/home/<user>/ruby_script/*.keys')
  for file in @files
    text = File.open(file, 'r').read
    text.each_line do |line|
      mergedfile << line
    end
  end
end

The idea is that the script will download public key files from github for our developers, merge them into an authorized_keys file which we'll then scp to our cloud servers.

The problem i'm having is that when the authorized_key file is generated, some of the ssh keys are on new lines, some are on the same line as others.

I've checked the downloaded files, and each key is on its' own line

How can I ensure that each key is on it's own line?

Thanks

4

3 回答 3

6

这将更容易cat在命令行中使用。您可以轻松地将所有文件连接到一个文件中。这是来自man cat命令行:

The command:

      cat file1 file2 > file3

will sequentially print the contents of file1 and file2 to the file file3,
truncating file3 if it already exists.  See the manual page for your shell
(i.e., sh(1)) for more information on redirection.

您可以轻松地从目录中的文件数组创建适当的命令,然后创建命令并通过反引号或%x命令在子 shell 中执行它。

就像是:

require 'dir'

files = Dir['/path/to/files.*'].select{ |f| File.file?(f) }.join(' ')
`cat #{ files } > new_file`

您的原始代码可以更简洁地重写为:

File.open('authorized_keys','a') do |mergedfile|
  Dir.glob('/home/<user>/ruby_script/*.keys').each do |file|
    mergedfile.write(File.read(file))
  end
end

您的代码的区别(和问题)是read语句。这会将整个文件拉入内存。如果该文件大于可用内存,您的程序将停止。很糟糕。有一些方法可以使用foreach而不是解决这个问题read,例如:

File.open('authorized_keys','a') do |mergedfile|
  Dir.glob('/home/<user>/ruby_script/*.keys').each do |file|
    File.foreach(file) do |li|
      mergedfile.write(li)
    end
  end
end
于 2013-09-05T20:28:30.183 回答
2

用于String#chomp删除尾随换行符,然后添加换行符("\n"$/):

"abc\n".chomp + "\n" # => "abc\n"
"abc".chomp + "\n" # => "abc\n"

mergedfile << line.chomp + "\n"
于 2013-09-05T14:59:20.580 回答
1

文件中除最后一行之外的行肯定会以结束符终止(否则,它们将不会被识别为一行),因此您的问题是文件的结尾不一定是结束符。为确保这一点,更改行

text = File.open(file, 'r').read

text = File.open(file, 'r').read.sub(/#$/?\z/, $/)
于 2013-09-05T15:00:33.073 回答