简体   繁体   中英

List directories that begin with a pattern

I have a directory with thousands of sub-directories.

Each subdirectory begins with a URL name, for example: /australia.gov.au_about-australia

I want to get a list of all the sub-directories that begin with a certain string, eg "australia.gov.au".

It appears that the list.dirs function does not allow for pattern matching?

I have tried the following, to no avail:

testSite <- "australia.gov.au"
list.files(paste0("main-directory/",paste0("^[",testSite,"]")), 
    full.names = TRUE, recursive=TRUE, ignore.case = TRUE)`

You can use Filter to filter your directory list

testSite <- "australia.gov.au"
Filter(function(x) grepl(paste0("^", gsub(".", "\\.", testSite, fixed=TRUE)), x),
    list.dirs())

We do some extra work to convert your URL to a regular expression to do the matching.

Following @MrFlick's answer for the first part, but simplifying the rest slightly:

 re <- paste0("^", gsub(".", "\\.", testSite, fixed=TRUE))
 grep(re,list.dirs(),value=TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM