Cakephp files and Folder class with regex to find file

I am creating some kind of wrapper for deleting backup files. I am using to create a backup of the original file using the "bkp" keyword. It can be anywhre in the filename like this: ["abc.bkp.ctp", "abc-bkp.ctp", abc_bkp.ctp "," bkp_abc.ctp "] . I mean any way I want to delete everything files with shell. I am using Cakephp Files N Folder Class " http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html " How do I write a regex to search for these files ...

What is my shell logic.

    public function removeBkp() {
        $path = BASE_PATH . DS . APP_DIR . DS;
        $count = 0;

        $this->out("", 2);
        $this->out("-------------------------------------", 1);
        $this->out("Path : " . $path, 1);
        $this->out("FILES DETAILS", 1);
        $this->out("-------------------------------------", 2);
        $dir = new Folder($path);
        // Need to seach bkp files here 
        $defaultFiles = $dir->findRecursive("(bkp)");

        $results = $defaultFiles;
        if ($results == null || empty($results)) {
            $this->out("No file to delete.", 3);
        } else {
            foreach ($results as $file) {
                // unlink($file);
                $this->out("File removed - " . $file, 1);
                $count++;
            }
            $this->out("Total files: " . count($results), 1);
        }
    }

      

+3


source to share


1 answer


You can match all filenames with this regex:

([\w._-]*bkp[\S]*?\.ctp)

      

Assuming only ._-

used to split files upwards, you may need to add more to this character class.

This regex also assumes that the file always ends with ctp.



Demo: https://regex101.com/r/tB9nM9/1

EDIT: If you want to match any extension, you can generalize the extension with \w{3}

. Where 3 is the length, you can add variance if necessary, but more specific is usually better.

([\w._-]*bkp[\S]*\.\w{3})

      

DEMO: https://regex101.com/r/tB9nM9/2

+1


source







All Articles