Comment/Delete all lines that contains a particular string.

Help
2014-07-26
2014-07-27
  • Hi,
    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.

    SOLVED

    import Npp
    
    # notepad.open('teste.txt')
    lines = editor.getText().split()
    current_line_number = 0
    res = 0
    
    editor.gotoPos(0)
    for i in range (len(lines)):
        editor.searchAnchor()
        res = editor.searchNext(0, 'MIPS')
        if res != -1:
            current_line_number = editor.lineFromPosition(editor.getCurrentPos())
            editor.gotoLine(current_line_number)
            editor.addText(' # ')
            editor.gotoLine(current_line_number + 1)
            editor.searchAnchor()
    
     
    Last edit: Dave Brotherstone 2014-07-27
  • (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

    editor.gotoPos(0)
    editor.searchAnchor()
    last_found_position = editor.searchNext(0, 'MIPS')
    while last_found_position != -1:
        last_found_line = editor.lineFromPosition(last_found_position)
        editor.gotoLine(last_found_line)
        editor.addText(' # ')
        editor.gotoLine(last_found_line + 1)
        editor.searchAnchor()
        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.

    Cheers,
    Dave.