如何从文件中删除行而不在ruby中创建临时文件?

如何从文件中删除行而不在ruby中创建临时文件?,ruby,Ruby,我需要用ruby按顺序删除一行文件,但没有成功 如果我用w+标志打开文件,它将完全为空,如果我用r+标志打开文件,则什么也不会发生。 我甚至试着用sed的系统命令来做,但也没有结果。 怎么了 $ cat teste.txt foo bar - This is by ruby way: $ cat ruby.rb #!/usr/bin/ruby path = '/home/paulosgf/hack/metasploit/teste.txt' File.open(path, 'r+') d

我需要用ruby按顺序删除一行文件,但没有成功

如果我用w+标志打开文件,它将完全为空,如果我用r+标志打开文件,则什么也不会发生。 我甚至试着用sed的系统命令来做,但也没有结果。 怎么了

$ cat teste.txt 
foo
bar

- This is by ruby way:
$ cat ruby.rb 
#!/usr/bin/ruby

path = '/home/paulosgf/hack/metasploit/teste.txt'
File.open(path, 'r+') do |file|
    file.each do |line|
        puts(line)
        line.gsub(/^.$\n/, '')
    end
file.close()
end

$ ./ruby.rb 
foo
bar

$ cat teste.txt (nothing happens)
foo
bar

- This is by sed way:
$ cat sed.rb 
#!/usr/bin/ruby

path = '/home/paulosgf/hack/metasploit/teste.txt'
File.open(path, 'r+') do |file|
    file.each do |line|
        puts(line)
        system("sed -i", "/#{line}/d #{path}")
    end
file.close()
end

$ ./sed.rb 
foo
bar

$ cat teste.txt 
foo
bar

我需要获得下一行,运行一些处理并在结尾删除这些行,但所有行仍保留在文件中。

我在另一个论坛上找到了解决方案。 [ 它只需要改变焦点:

[ paulosgf /home/paulosgf/hack/metasploit ] $ cat teste.txt 
john
doe
foo
bar
[ paulosgf /home/paulosgf/hack/metasploit ] $ cat delFirst.rb 
#!/usr/bin/ruby

path = '/home/paulosgf/hack/metasploit/teste.txt'
remains=''
line=''
each=''

File.foreach(path) { |each|
File.open(path, 'r') {|file| line=file.gets; remains=file.read}
puts("#{line}")
File.open(path, 'w+') {|file| file.write(remains)}
}
[ paulosgf /home/paulosgf/hack/metasploit ] $ ./delFirst.rb 
john
doe
foo
bar
[ paulosgf /home/paulosgf/hack/metasploit ] $ cat teste.txt 
[ paulosgf /home/paulosgf/hack/metasploit ] $ 

file.each do | line |将每一行作为字符串提供给您。line.gsub返回一个新字符串。您上面的代码正在尝试删除文件中的每一行。如果这真的是目的,那么为什么不只是…删除文件?@TomLord我不想删除整个文件,因为我需要一次处理一行。有什么原因您不能一次只处理一行吗一次,然后删除文件?除非您需要暂停,并选择您停止的位置,但无法重新运行整个过程,否则这可能是一个更简单的实现。这是一个巨大的IP列表。我获取下一个IP并对其执行安全扫描。最后,我需要从列表中删除此IP,因为如果脚本崩溃,我可以从下一个IP重新启动,不要重复上一个IP。