在Unix命令行中使用变量

时间:2016-09-30 14:11:02

标签: r unix environment-variables

我试图让自己的生活变得更轻松,但它还没有奏效。我想要做的是以下几点:

注意:我在unix服务器上运行R,因为我的其余部分都在R中。这就是system(" ")

的原因
system("TRAIT=haptoglobin")

system("grep var.resid.anim rep_model_$TRAIT.out > res_var_anim_$TRAIT'.xout'",wait=T)

但是,这样做的结果是文件rep_model_.out被读取并且res_var_anim_.xout被创建,但需要读取rep_model_haptoglobin.out并且需要创建res_var_anim_haptoglobin.xout

当我在putty中运行完全相同的东西时(当然没有system(" ")),然后读取正确的文件并创建右输出。当我删除我创建的变量时,脚本也可以工作。但是,我需要多次这样做,所以变量对我来说非常方便,但是我无法让它工作。

2 个答案:

答案 0 :(得分:1)

此代码在控制台上不打印任何内容。

system("xxx=foo")
system("echo $xxx")

但以下情况确实如此。

system("xxx=foo; echo $xxx")

一旦完成对“system”的一次调用,系统就会忘记你的变量定义。

在你的情况下,尝试怎么样:

system("TRAIT=haptoglobin; grep var.resid.anim rep_model_$TRAIT.out > res_var_anim_$TRAIT'.xout'",wait=T)

答案 1 :(得分:0)

你可以将这一切保存在R:

grep_trait <- function(search_for, in_trait, out_trait=in_trait) {
  l <- readLines(sprintf("rep_model_%s.out", in_trait))
  l <- grep(search_for, l, value=TRUE) %>% 
  writeLines(l, sprintf("res_var_anim_%s.xout", out_trait))
}

grep_trait("var.resid.anim", "haptoglobin")

如果担心文件首先被读入内存(即如果它们是大文件),那么:

grep_trait <- function(search_for, in_trait, out_trait=in_trait) {
  fin <- file(sprintf("rep_model_%s.out", in_trait), "r")
  fout <- file(sprintf("res_var_anim_%s.xout", out_trait), "w")
  repeat {
    l <- readLines(fin, 1)
    if (length(l) == 0) break;
    if (grepl(search_for, l)[1]) writeLines(l, fout)
  }
  close(fin)
  close(fout)
}