I have a folder which contains files of the following names "5_45name.Rdata"
and "15_45name.Rdata"
.
I would like to list only the ones starting with "5", in the example above this means that I would like to exclude "15_45name.Rdata"
.
Using list.files(pattern="5_*name.Rdata")
, however, will list both of these files.
Is there a way to tell list.files() that I want the filename to start with a specific character?
Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.
Finding files by name is probably the most common use of the find command. To find a file by its name, use the -name option followed by the name of the file you are searching for. The command above will match “Document. pdf”, “DOCUMENT.
We need to use the metacharacter (^
) to specify the start of the string followed by the number 5. So, it can a more specific pattern like below
list.files(pattern ="^5[0-9]*_[0-9]*name.Rdata")
Or concise if we are not concerned about the _
and other numbers following it.
list.files(pattern = "^5.*name.Rdata")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With