Have rscript read or accept input from stdin

I see how Rscript performs the operations that I want when the file name is given as an argument, for example. if my rscript is called a script and contains:

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

Then I can run bash from the command line:

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

and successfully retrieve the contents of filename.Rmd recalled by me. If instead of passing the above argument a file name, for example filename.Rmd , I want to pass its text from stdin , I try to change my script to read from stdin:

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

but I don’t know how to build a command line call for this case. I tried the pipeline in the content:

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

and also tried to redirect:

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

and anyway I get an error:

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

(I also tried open(file("stdin")) ). I'm not sure if I am building Rscript incorrectly or an invalid command line argument, or both.

+7
bash r stdin
source share
1 answer

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

 #!/usr/bin/Rscript writeLines(readLines(file("stdin"))) 
+7
source share

All Articles