Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp Files and Folder class with regex to search for file

Tags:

regex

cakephp

I am creating some sort of shell for removing backup files. I use to create backup of original file using keyword 'bkp'. It could be anywhre in file name either like this ["abc.bkp.ctp", "abc-bkp.ctp", abc_bkp.ctp", "bkp_abc.ctp"]. I mean any way. I wish to remove all files using shell. I am using Cakephp's Files N Folder Class "http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html". How would I write regex to search for these files.

Whats my shell logic is.

    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);
        }
    }
like image 675
Sankalp Avatar asked Nov 17 '25 00:11

Sankalp


1 Answers

You can match all filenames with this regex:

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

Assuming only ._- are used to split the files up, you may need to add more to that character class.

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

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

EDIT: If you wish to match any extension, you can generalise the extension with \w{3}. Where 3 is the length, you can add variance here if needed, but more specific is usually better.

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

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

like image 54
melwil Avatar answered Nov 19 '25 14:11

melwil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!