简体   繁体   English

R中的带引号的mac shell命令

[英]mac shell commands in R with quotes

I am using RStudio on Mac. 我在Mac上使用RStudio。 I want to execute a shell command (terminal command) from within a R script file. 我想从R脚本文件中执行Shell命令(终端命令)。 I am using the system function in R to do this. 我正在R中使用系统功能来执行此操作。

However, to take a step further, I have a shell command that has a loop and passes some parameters. 但是,要更进一步,我有一个shell命令,该命令具有一个循环并传递一些参数。 To pass these parameters, I need to use quote marks. 要传递这些参数,我需要使用引号。 As system function already takes quotes, these second set of quotes are giving a syntax error. 由于系统功能已经使用了引号,因此第二组引号给出了语法错误。 For example 例如

  1. simple call @ terminal : mkdir ch; @终端简单调用:mkdir ch; when translated to R will be 当翻译成R时将是

    system("mkdir ch") 系统(“ mkdir ch”)

in Rscript makes a ch folder in workspace. 在Rscript中在工作区中创建一个ch文件夹。

  1. loop call @ terminal = 循环调用@终端=

    for file in *.pdf; 用于* .pdf中的文件; do pdftotext "$file" "$file.txt"; 做pdftotext“ $ file”“ $ file.txt”; done. 完成。

in terminal the above command will loop the 'pdftotext' command on each file in the directory. 在终端中,以上命令将在目录中的每个文件上循环执行“ pdftotext”命令。 But as you notice, this call already has quotes (file variable) and conflicts with quotes of system("") function in R 但是,您注意到,此调用已经带有引号(文件变量),并且与R中system(“”)函数的引号冲突

How can I do this shell command with a loop call into R system function? 如何通过循环调用R系统功能来执行此Shell命令?

The problem is that once you include a second double quote, you're telling R to close the string. 问题在于,一旦您包含了第二个双引号,便要告诉R关闭字符串。 Take this sample string as an example: 以以下示例字符串为例:

x = "I use air "quotes" like this..."
# Error: unexpected symbol in "x = "I use air "quotes"

It doesn't like the embedded double quotes. 它不喜欢嵌入的双引号。 But, if we replace the double quotes with single quotes, our problem goes away: 但是,如果我们将双引号替换为单引号,我们的问题就解决了:

x = 'I use air "quotes" like this...' # or
x = "I use air 'quotes' like this..."

Either way, the two types of quotes essentially ignore each other and all is well. 无论哪种方式,两种类型的引号本质上都是相互忽略的,并且一切都很好。 However, sometimes that's not enough. 但是,有时这还不够。 What if you have embedded quotes inside of embedded quotes? 如果您在嵌入引号内嵌入了引号怎么办?

x = "python some_syntax.py '["Me", "You", "Him"]'"
# Error: unexpected symbol in "x = "python some_syntax.py '["Me"

We can fix this problem by escaping quotes with a backslash. 我们可以通过用反斜杠转义引号来解决此问题。 I'm going to reverse where I use single and double quotes, though, to minimize the number of escapes needed. 不过,我将在使用单引号和双引号的地方进行反向操作,以减少所需的转义次数。

x = "python some_syntax.py \"['Me', 'You', 'Him']\""

Again, all is well. 同样,一切都很好。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM