【发布时间】:2017-08-18 02:10:18
【问题描述】:
我有一堆文件。它们的命名如下:
BNT_20170301131740322_123456.csv, BNT_20170301131740322_7891011.csv
在这个文件名中,从第 5 个字符到第 12 个字符是日期,第 13 个和第 14 个字符是小时。其余的都是动态生成的,并且不断变化。在上面的例子中,日期是 2017 年 3 月 1 日,小时是 13。
任务 1: 我必须通过压缩与特定日期和时间匹配的所有文件来创建 tar 文件。因此,根据生成文件的日期和时间,我将有多个 tar 文件作为输出。
任务 2: 下一个任务是以特定模式命名 tar 文件。 每个 tar 文件应按以下模式命名:
BNT_2017030111_2.tar
在上面的名称中,我们可以看到保留的“BNT_”后跟日期和小时,_(下划线)后面的 2 表示 tar 中与日期和时间匹配的文件数。在上面的示例中,名称表明文件的日期为 2017 年 3 月 1 日,并且小时参数 11 被一起 tar 并且 tar 中有 2 个文件。
到目前为止我做了什么:
#set the working directory
setwd("/home/mycomp/Documents/filestotar/")
#list all files
files <- list.files(pattern = ".csv")
我列出了所有文件的名称以便重现
files <- c("BNT_20170301000000790_123456.csv", "BNT_20170301000000887_7891011.csv",
"BNT_20170301000000947_7430180.csv", "BNT_20170301000001001_2243094.csv",
"BNT_20170301000001036_14195326.csv", "BNT_20170301000001036_14770776.csv",
"BNT_20170301000001078_10692013.csv", "BNT_20170301000001089_2966772.csv",
"BNT_20170301000001100_10890506.csv", "BNT_20170301000001576_7430180.csv")
我的代码:
library(stringr)
#extract date and time and set the pattern to identify the files in the folder
#extracts date from the file name
d <- substr(files, 5,12)
#extracts hour from the file name
e <- substr(files, 13,14)
#creates a pattern that can be used to identify the files matching the pattern.
pat <- paste("BNT","_",unique(d),unique(e),sep="")
#creates the count of files with unique hour parameter. This will be used to create the name for the tar file.
f <- table(paste(d,e,sep=""))
#create unique names for the tar files
g <- unique(paste("BNT",unique(d),unique(e),f,sep="_"))
#pasting the extension .tar to the name of the file
h <- paste(g,".tar",sep="")
#create a nested forloop to tar the files recursively
for (name in h) {
for (i in seq_along(pat)) {
filestotar = for (i in seq_along(pat)) {list.files(path = "/home/mycomp/Documents/filestotar/", pattern = pat[i])}
}
tar(tarfile = name, files = filestotar)
}
以上创建了所需数量的 tar 文件。但是 tar 文件将文件夹中的所有文件包含在第一个 tar 本身中,并递归地将所有新 tar 文件与文件夹中的原始文件包含在所有后续 tar 文件中。
例如,第一个 tar 文件包含所有 csv 文件,而不是仅匹配模式 pat 的那些文件
第二个 tar 文件包含第一个 tar 文件 + 它包含所有 csv 文件,而不仅仅是那些与模式 pat 匹配的文件。
现在,每个创建的 tar 文件都会继续进行,最后一个 tar 文件包含所有创建的 tar 文件 + 所有与 pat 匹配的文件。
所需的输出是:
仅对文件名中与日期和小时匹配的文件进行 tar,并用 BNT_ + 日期 + 小时 + 文件数 + .tar 命名它们,如下所示:
BNT_2017030111_2.tar
已创建包含虚拟文件的文件夹...以防万一:
https://drive.google.com/open?id=0BwPrNXRo3C1aaUN2WmMtS3dpZ1U
【问题讨论】: