我有以下打印声明:
sudo apachectl -k restart
当我打印语句stat <- paste("scp /home/owner/run2/reports/", x, "_EC.zip /home/adam/Desktop/Link\ to\ Software\ Project/Experiments/exp_20/run2/results/", sep = "")
时,得到以下结果:
stat
如您所见,scp /home/owner/run2/reports/modelTable_EC.zip /home/adam/Desktop/Link to Software Project/Experiments/exp_20/run2/results/
部分打印时没有Link\ to\ Software\ Project
符号,这是我在终端机(ubuntu终端机)中使用此路径时所需的。
如何避免这个问题?
答案 0 :(得分:1)
由于您希望在终端中使用它,因此可以将有问题的路径放在(单引号)中。
x <- "modelTable"
stat <- paste("scp /home/owner/run2/reports/", x, "_EC.zip '/home/adam/Desktop/Link\ to\ Software\ Project/Experiments/exp_20/run2/results/'", sep = "")
## Using cat prints it without the extra quotes
cat(stat)
## scp /home/owner/run2/reports/modelTable_EC.zip '/home/adam/Desktop/Link to Software Project/Experiments/exp_20/run2/results/'
答案 1 :(得分:1)
我建议您将命令行视为由长字符串组成的一系列命令和参数。 R的system
在这里没有道理,system2
几乎没有更好:尽管它鼓励将命令视为其组成部分(例如,命令,连字符或文件/路径)的向量,它只是天真地将字符串连接在一起,而无需考虑使用shell引用或您拥有什么。
我使用shQuote
进行防御性处理。好处是,即使文件/路径不需要它们,它也可以在文件/路径上运行,因此您不能有效地过度使用它。 (通常不需要将其与连字符参数一起使用,但是某些工具(很多吗?)无论如何都不在乎和无法正常工作,因此从技术上讲
$ ssh "-v" "/home/owner/..." "/home/adam/Desktop/..."
在shell中应该可以正常工作。
因此,shQuote
类似于路径的任何事物。 (我说“类似于”的假设是程序是通过程序形成的……静态参数并不是严格需要它的,尽管正如我之前所说的那样,这样做并不会有伤害。)
cmd <- c("scp", shQuote(paste0("/home/owner/run2/reports/", x, "_EC.zip")),
shQuote("/home/adam/Desktop/Link\ to\ Software\ Project/Experiments/exp_20/run2/results/"))
cmd
# [1] "scp"
# [2] "\"/home/owner/run2/reports/modelTable_EC.zip\""
# [3] "\"/home/adam/Desktop/Link to Software Project/Experiments/exp_20/run2/results/\""
要将其打印到控制台,以便您可以将其复制并粘贴到终端/外壳中:
cat(paste(cmd, sep = " "), "\n")
# scp "/home/owner/run2/reports/modelTable_EC.zip" "/home/adam/Desktop/Link to Software Project/Experiments/exp_20/run2/results/"
或者您可以直接从R运行它:
system2(cmd[1], args = cmd[-1])
答案 2 :(得分:0)
一个更简单的可重现示例
x <- "modelTable"
stat <- paste0("reports/", x, "_EC.zip /home/link\ to\ Software\ Project/Experiments/")
> stat
[1] "reports/modelTable_EC.zip /home/link to Software Project/Experiments/"
可以使用“ /”吗?
stat1 <- paste0("reports/", x, "_EC.zip /home/link/ to/ Software/ Project/Experiments/")
stat1
#[1] "reports/modelTable_EC.zip /home/link/ to/ Software/ Project/Experiments/"
其他转义符号\
stat2 <- paste0("reports/", x, "_EC.zip /home/link\\ to\\ Software\\ Project/Experiments/")
stat2
#[1] "reports/modelTable_EC.zip /home/link\\ to\\ Software\\ Project/Experiments/"