最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - Is there a way to find files that don't start with a certain string? - Stack Overflow

programmeradmin0浏览0评论

I'd like to try and pull all files in my working directory that don't begin with the string "CONVERTED" -- so I'd like for list.files() to find "x.csv" but not "CONVERTEDx.csv" (my program will write a .csv file later that has that naming convention).

I tried:

x <- list.files(pattern = "^(!CONVERTED)*.csv")

This creates an empty character variable.

I'd like to try and pull all files in my working directory that don't begin with the string "CONVERTED" -- so I'd like for list.files() to find "x.csv" but not "CONVERTEDx.csv" (my program will write a .csv file later that has that naming convention).

I tried:

x <- list.files(pattern = "^(!CONVERTED)*.csv")

This creates an empty character variable.

Share Improve this question edited Feb 5 at 21:24 Wiktor Stribiżew 627k41 gold badges496 silver badges611 bronze badges asked Feb 5 at 19:16 BlueGyroscopeBlueGyroscope 111 bronze badge 0
Add a comment  | 

3 Answers 3

Reset to default 2

grep would come in handy on this one to get the files that do not match the pattern instead of trying to get all files and then filter in more than one line. invert gives the opposite of the pattern. value gives the filenames that do not match the pattern.

x <- grep(list.files(pattern="\\.csv"), pattern='^CONVERTED', invert=TRUE, value=TRUE)

You almost have a negative lookahead there, just missing a ?.
Regex for "start of the string that is not followed by CONVERTED" would be ^(?!CONVERTED). But we'd need to switch to Perl / PCRE regex for this to work, unfortunatly not an option for list.files().

As an alternative, there's fs::dir_ls() which uses grep() and forwards extra arguments (e.g. perl = TRUE):

fs::dir_tree()
#> .
#> ├── CONVERTEDx.csv
#> └── x.csv

fs::dir_ls(regexp = "^(?!CONVERTED).*\\.csv$", perl = TRUE)
#> x.csv

To

pull all .csv files in my working directory that don't begin with the string "CONVERTED"

You can always do

x <- list.files(pattern = "\\.csv$") # get all CSV files
x <- x[!startsWith(x, "CONVERTED")]

or

x <- list.files(pattern = "\\.csv$")[!grepl("^CONVERTED", list.files(pattern = "\\.csv$"))]
发布评论

评论列表(0)

  1. 暂无评论