尝试将文件夹中多个文件的内容附加到新文件

use*_*762 0 ruby

我正在尝试在 ruby​​ 中创建一个脚本,该脚本读取文件夹中的文件,并将它们合并到一个单独的文件中。

这就是我想出的

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
Run Code Online (Sandbox Code Playgroud)

这个想法是,该脚本将为我们的开发人员从 github 下载公钥文件,将它们合并到authorized_keys 文件中,然后我们将其 scp 到我们的云服务器。

我遇到的问题是,当生成authorized_key 文件时,一些ssh 密钥位于新行,一些与其他密钥位于同一行。

我检查了下载的文件,每个密钥都在自己的行上

如何确保每个键都在自己的行上?

谢谢

the*_*Man 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.
Run Code Online (Sandbox Code Playgroud)

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

就像是:

require 'dir'

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

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

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

您的代码的差异(和问题)在于声明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
Run Code Online (Sandbox Code Playgroud)