试图删除文件列表

时间:2010-05-13 13:17:15

标签: r grep

我有一个文件列表,我正在尝试提取所有layer1 _ * .grd文件。有没有办法在一个grep表达式中执行此操作?

lof <- c("layer1_1.grd", "layer1_1.gri", "layer1_2.grd", "layer1_2.gri", 
"layer1_3.grd", "layer1_3.gri", "layer1_4.grd", "layer1_4.gri", 
"layer1_5.grd", "layer1_5.gri", "layer2_1.grd", "layer2_1.gri", 
"layer2_2.grd", "layer2_2.gri", "layer2_3.grd", "layer2_3.gri", 
"layer2_4.grd", "layer2_4.gri", "layer2_5.grd", "layer2_5.gri", 
"layer3_1.grd", "layer3_1.gri", "layer3_2.grd", "layer3_2.gri", 
"layer3_3.grd", "layer3_3.gri", "layer3_4.grd", "layer3_4.gri", 
"layer3_5.grd", "layer3_5.gri", "layer4_1.grd", "layer4_1.gri", 
"layer4_2.grd", "layer4_2.gri", "layer4_3.grd", "layer4_3.gri", 
"layer4_4.grd", "layer4_4.gri", "layer4_5.grd", "layer4_5.gri")

我尝试分两步执行此操作:

list.of.files <- list.files(pattern = c("1_"))
list.of.files <- list.of.files[grep(".grd", list.of.files)]

有人可以告诉我如何用grep一步完成这项工作吗?我天真地尝试将list()和c()传递给grep但是,你可以想象,它不起作用。

list.of.files <- list.files()
list.of.files <- list.of.files[grep(list("1_", ".grd"), list.of.files)]

2 个答案:

答案 0 :(得分:3)

这应该适合你:

> lof[grep("layer1_.*.grd", lof)]
[1] "layer1_1.grd" "layer1_2.grd" "layer1_3.grd" "layer1_4.grd" "layer1_5.grd"

另外,只是为了澄清您的术语:您的文件列表实际上不是list;它是character向量。

答案 1 :(得分:2)

stringr替代方案为lof[str_detect(lof, "layer1_.*.grd")]

事实上,在这种情况下,您可以更加具体地了解丢失的字符,因此"layer1_[[:digit:]].grd"可以作为此处的模式使用,如果lof非常长,可能会更快。