如何将多个文件传递给命令函数并将它们输出到不同的文件?

时间:2017-11-14 13:09:31

标签: r bash file

我有一个由50个文件组成的目录,这里有一个关于文件名称的摘录:

    input1.txt
    input2.txt    
    input3.txt
    input4.txt

我在R中编写脚本,但我在其中使用“系统”使用bash命令 我有一个系统命令X,它接受一个文件并将其输出到一个文件 例如:

X input1.txt output1.txt

我希望input1.txt输出到output1.txt,输入2.txt输出到output2.txt等。

我一直在尝试这个:

    for(i in 1:50)
    {
     setwd("outputdir");
     create.file(paste("output",i,".txt",sep=""));
     setwd("homedir");
     system(paste("/usr/local/bin/command" , paste("input",i,".txt",sep=""),paste("/outputdir/output",i,".txt",sep="")));
    }

我做错了什么?我在系统行遇到错误,它说不正确的字符串常量,我不明白..我是否以错误的方式应用系统命令?

有没有办法获取所有输入文件和输出文件而无需通过粘贴命令将它们放入系统内?

1 个答案:

答案 0 :(得分:0)

在R中有一种非常简单的方法可以在不使用系统命令的情况下将文件复制到新目录。这还具有在不同操作系统上具有交叉能力的优点(只需更改文件结构)。

修改后的代码来自:"Copying files with R" by Amy Whitehead

使用运行文件1:50的方法我在这里有一些psudocode。您需要将current.folder和new.folder更改为

# identify the folders
current.folder <- "/usr/local/bin/command"
new.folder <- "/outputdir/output"

# find the files that you want
i <- 1:50
# Instead of looping we can use vector pasting to get multiple results at once!
inputfiles <- paste0(current.folder,"/input",i,".txt")
outputfiles <- paste0(new.folder,"/output",i,".txt")

# copy the files to the new folder
file.copy(inputfiles, outputfiles)