The use of dollar sign '$' after file type when listing files

Viewed 480

I have seen a lot of people using the dollar sign $ after .csv when listing a bunch of files, e.g.

filenames <- list.files(path='fake/path/name',pattern='*.csv$')

However, when I was working on a project, it worked for me without the dollar sign. My code is

filenames <- list.files(path='fake/path/name',pattern='*.csv')

I haven't found a clear explanation of what this dollar sign does exactly in this situation. All of my files were listed in both usages. Does anyone know what difference this dollar sign makes?

3 Answers

The dollar sign is an end-of-line marker in a regular expression. pattern='*.csv$' matches only file names that end with ".csv", so that e.g. if you had backup files called foo.csv.bak or foo.csv~, these wouldn't get included.

The $ is a metacharacter in regex to specify the end ($) of the string. Usually the csv will be at the end of the file name. Thus, it works. But, there are certain cases, where we may find a random csv character and gives erroneous results.

In addition, the OP was using .csv. Here, again, this is problematic as . is a metacharacter that matches any other character. A more correct version will be \\.csv$ i.e. escape the . to evaluate it literally

Related