请帮助,我被困在这里---

irb> a = "line of text\n  line two\n  line three"
irb> system("cat > test_file << #{a}")
cat: of: No such file or directory
cat: text: No such file or directory
=> false
有帮助吗?

解决方案

您需要引用插值参数:

system("cat > test_file << \"#{a}\"")

并且,cat期望一个文件名,而不是一些文本附加到test_file,所以,这可以像我想的那样工作:

system("echo \"#{a}\" >> test_file")

如果你想在纯Ruby中这样做,请告诉我,我会给你一个例子。

其他提示

将a写入名为“testfile”的文件:

File.open("testfile", "w") do |io| io.print a done

JesperE已经涵盖了直接写入文件。要写入进程(在本例中为“cat”进程),请使用popen。

IO.popen("cat > foo", "w") do
    |f|
    f.write("line1\nline2\n")
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top