6

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?

Denis Sadowski
  • 3,035
  • 5
  • 24
  • 26

2 Answers2

9

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!

Community
  • 1
  • 1
littlegreen
  • 7,290
  • 9
  • 45
  • 51
  • 1
    Use the PathMatchSpec to exclude a file match pattern if the pattern starts with "-" a minus sign for instance. That will need say two bool variables: matched and excluded. The method will not have a return from within the loop. The final return will be !excluded && matched – Robert Cutajar Oct 15 '12 at 16:15
3

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()
Community
  • 1
  • 1
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • 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 Feb 03 '10 at 06:50