List files in ruby

Using the Dir and File we are able to create a function to list the content of a given path:

    def list_files( path, filter = '', full_names = FALSE )
        if full_names == TRUE
            files = Dir.entries(path).select{ | ff | ff != '.' && ff != '..' }.map{ | ff | File.join(path, ff) }
        else
            files = Dir.entries(path).select{ | ff | ff != '.' && ff != '..' }
        end

        if filter.class != ''
            files = files.select{ | ff | ff[filter] }
        end

        return files
    end

The previous function, moreover allows to get the full name of the files (in base of the given path) and also to filter the result given a regular expression.

For example, having a folder with:

    [carleshf@lambdafunction Data]$ ll aligned/
    -rw-rw----+ 1 carleshf carleshf 2200853068 apl 21 06:06 mRNA10_AGTTCC_f2.bam
    -rw-rw----+ 1 carleshf carleshf    4778016 apl 21 06:06 mRNA10_AGTTCC_f2.bam.bai
    -rw-rw----+ 1 carleshf carleshf 1621816053 apl 21 06:06 mRNA10_CAGATC_f2.bam
    -rw-rw----+ 1 carleshf carleshf    4774552 apl 21 06:06 mRNA10_CAGATC_f2.bam.bai
    -rw-rw----+ 1 carleshf carleshf 2195712479 apl 21 06:06 mRNA10_CCGTCC_f2.bam
    -rw-rw----+ 1 carleshf carleshf    4445664 apl 21 06:06 mRNA10_CCGTCC_f2.bam.bai
    ...

We can list the .bam files with:

    list_files('aligned', full_names = TRUE, filter = /.bam$/)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: