bash 让 Rscript 读取或从 stdin 获取输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22796434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:04:28  来源:igfitidea点击:

Have an Rscript read or take input from stdin

rbashstdin

提问by cboettig

I see how to have an Rscript perform the operations I want when given a filename as an argument, e.g. if my Rscript is called scriptand contains:

当给定文件名作为参数时,我看到如何让 Rscript 执行我想要的操作,例如,如果我的 Rscript 被调用script并包含:

#!/usr/bin/Rscript 
path <- commandArgs()[1]
writeLines(readLines(path))

Then I can run from the bash command line:

然后我可以从 bash 命令行运行:

Rscript script filename.Rmd --args dev='svg'

and successfully get the contents of filename.Rmdechoed back out to me. If instead of passing the above argument a filename like filename.RmdI want to pass it text from stdin, I try modifying my script to read from stdin:

并成功地将 echoed 的内容filename.Rmd返回给我。如果不是像filename.Rmd我想将文本传递给上述参数那样传递文件名stdin,我尝试修改我的脚本以从标准输入读取:

#!/usr/bin/Rscript 
writeLines(file("stdin"))

but I do not know how to construct the commandline call for this case. I tried piping in the contents:

但我不知道如何为这种情况构建命令行调用。我尝试在内容中使用管道:

cat filename.Rmd | Rscript script --args dev='svg'

and also tried redirect:

并尝试重定向:

Rscript script --args dev='svg' < filename.Rmd

and either way I get the error:

无论哪种方式,我都会收到错误消息:

Error in writeLines(file("stdin")) : invalid 'text' argument

(I've also tried open(file("stdin"))). I'm not sure if I'm constructing the Rscript incorrectly, or the commandline argument incorrectly, or both.

(我也试过open(file("stdin")))。我不确定我是否错误地构建了 Rscript,或者命令行参数错误,或者两者都有。

回答by Gavin Simpson

You need to read text from the connection created by file("stdin")in order to pass anything useful to the textargument of writeLines(). This should work

您需要从由创建的连接中读取文本file("stdin"),以便将任何有用的内容传递给 的text参数writeLines()。这应该工作

#!/usr/bin/Rscript 
writeLines(readLines(file("stdin")))