Comment/Delete all lines that contains a particular string.

  • Rodrigo Oliveira

    I´m struggling to do a script that comment all lines containing the string "test" on my files.

    I try to do something like that, but it´s not working because a i do not know when the search is done.


    import Npp
    lines = editor.getText().split()
    current_line_number = 0
    res = 0
    for i in range (len(lines)):
        res = editor.searchNext(0, 'MIPS')
        if res != -1:
            current_line_number = editor.lineFromPosition(editor.getCurrentPos())
            editor.addText(' # ')
            editor.gotoLine(current_line_number + 1)
    Last edit: Dave Brotherstone 2014-07-27
  • Dave Brotherstone

    (Hope you don't mind, I fixed your formatting so it's easier to read)

    Whilst this works, it's much more complicated than it needs to be.

    There's actually a one line solution to this, but we'll try and stick to your method first.

    As you have discovered, searchNext returns -1 when it doesn't find anything. You can actually end the search there. If a line has your search text in twice, you'd actually add the ' # ' in twice, for example. Because the search automatically continues from the last searchAnchor() position, you don't need to worry about splitting the lines up.

    The following is a complete script that does the same thing

    last_found_position = editor.searchNext(0, 'MIPS')
    while last_found_position != -1:
        last_found_line = editor.lineFromPosition(last_found_position)
        editor.addText(' # ')
        editor.gotoLine(last_found_line + 1)
        last_found_position = editor.searchNext(0, 'MIPS')

    This script is more efficient, as it doesn't matter how many lines there are, it just searches through and jumps to the next match.

    However, as I mentioned, you can actually peform the whole script in one line, using a regular expression.

    editor.rereplace('^.*MIPS.*$', ' # $0')

    The explaination:

    ^ means beginning of the line
    .* means any character, any amount of times (including none)
    MIPS is your search string
    .* again means followed by any character, any amount of times
    $ means the end of the line

    Then replace with ' # ', followed by $0, which means the whole match.

    I hope that helps explain a little.



Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

No, thanks