views:

355

answers:

2

Hi All,

I was wondering if it was possible to list an exclusion within the file filters in the "find in files" functionality of Notepad++.

For example the following will replace Dog with Cat in all files.

Find what: Dog

Replace with: Cat

Filters: *.*

What I would like to do is replace Dog with Cat in all files except those in .sh files.

Is this possible?

+2  A: 

I think something like a "negative selector" does not exist in Notepad++.

I took a quick look at the 5.6.6 source code and it seems like the file selection mechanism boils down to a function called getMatchedFilenames() which recursively runs through all the files below a certain directory, which in turn calls the following function to see whether the filename matches the pattern:

bool Notepad_plus::matchInList(const TCHAR *fileName, const vector<generic_string> & patterns)
{
    for (size_t i = 0 ; i < patterns.size() ; i++)
    {
        if (PathMatchSpec(fileName, patterns[i].c_str()))
            return true;
    }
    return false;
}

As far as I can determine, PathMatchSpec does not allow negative selectors.

It is however possible to enter a list of positive filters. If you could make that list long enough to include all the extensions in your directory except .sh, you're also there.

Good luck!

littlegreen
+3  A: 

Great answer by littlegreen.
Unfortunate that Notepad++ can't do it.

This tested example will do the trick (Python). replace method thanks to Thomas Watnedal:

from tempfile import mkstemp
import glob
import os
import shutil

def replace(file, pattern, subst):
    """ from Thomas Watnedal's answer to SO question 39086 
        search-and-replace-a-line-in-a-file-in-python
    """
    fh, abs_path = mkstemp() # create temp file
    new_file = open(abs_path,'w')
    old_file = open(file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    new_file.close() # close temp file
    os.close(fh)
    old_file.close()
    os.remove(file) # remove original file
    shutil.move(abs_path, file) # move new file

def main():
    DIR = '/path/to/my/dir'

    path = os.path.join(DIR, "*")
    files = glob.glob(path)

    for f in files:
        if not f.endswith('.sh'):
            replace(f, 'dog', "cat")

if __name__ == '__main__':
    main()
Adam Bernier
Way cool. And then you can add the script to the list of executables in the Nppexec plugin. Real coders don't need GUI's :-)
littlegreen