我有文件的千從某個目錄中的文件:使用R,檢索的文件名,幷包含某些字符串
filenames <- list.files("D:/MessData_Source", pattern="*.DAT", full.names=TRUE)
.....
.....
[9998] "D:/MessData_Source/908-A0F7__01310012567794F.DAT"
[9999] "D:/MessData_Source/908-A0F7__01310015662858F.DAT"
[10000] "D:/MessData_Source/908-A0F7__01310015662859F.DAT"
....
....
掉那些超過1000個文件,我需要提取出只有那些文件名的文件,其包含某些字符串。
例如
filename_extracted <- list()
for (i in 1:length(filenames))
{
# search for those filenames that contain the strings with PartNo and MoNo and store in results
filename_extracted[[i]] <- substr(filenames[i],31,43)
}
上面我從31號提取文件名字符串43並將其存儲在filename_extracted是這樣的:
[[9993]]
[1] "1856955908850"
[[9994]]
[1] "1856955933372"
[[9995]]
[1] "1856955933372"
[[9996]]
[1] "1856955954613"
[[9997]]
[1] "1856955954613"
[[9998]]
[1] "1310012567794"
[[9999]]
[1] "1310015662858"
[[10000]]
[1] "1310015662859"
接下來,我需要比較filename_extracted我的要求清單,並將這些匹配的文件複製到另一個目錄。
required_list <- list()
df <-read.csv("PartNo_MoNo.csv") # full set
for (i in 1:length(df))
{
required_list[[i]] <- paste(df[i,1],df[i,2], sep="")
}
> required_list
[[1]]
[1] "1235235987252"
[[2]]
[1] "1897865985468"
如果有required_list和filename_extracted,我想匹配的文件複製到另一個目錄之間的匹配,我該怎麼辦呢?
謝謝。
嗨Beauvel&Dieter Menne上校,感謝您的回覆,我理解您的代碼......但我需要一些修改......,前10個字符並不總是「908-A0F7__」。它可以是「908-A0F7__01310015662859F.DAT」或「908-A062__01042105733247P.DAT」或「908-A050_A01042045683782P.DAT」或「108-0626_B09120015857047A.DAT」或「258-5141_B01963555909713F.DAT」或「108-0626_B09120015774259A.DAT」 。我們可以看到文件名總是包含29個字符,包括其擴展名.DAT。 –
爲此編輯!下一次在你的問題中提到它;) –
對不起...我仍然需要提取最後5個字符...並追加到commonFile ... suffix = substr(文件名,開始= 44,停止= 48)#最後5個字符.... commonFile = paste0(common_prefix,common_suffix,suffix) sapply(commonFile,function(u){file.path(storeDir,u),file.path(otherDir,u) )上面的代碼不起作用,它會複製所有內容 –