Community

    • Login
    • Search
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search

    find and replace automation in python

    Help wanted · · · – – – · · ·
    2
    3
    190
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Ruben Lara
      Ruben Lara last edited by

      Hi there,

      i need some help since i have to do a repetitive task at work every day, many times per day.

      i need to replace a series of 18 numbers which are consecutive, but different in every file i open.
      an idea of the script that i’m looking for is something like this:

      find: 0001
      replace: “numberX”
      find: 0002
      replace: “numberX+1”
      find:0003
      replace: “numberX+2”

      and so on until get to
      find: 0018
      replace: “numberX+17”

      note: the numbers 0001 to 0018 will always be in the raw file i use. therefore, it will always have to find the same numbers (0001 to 0018) and replace them with the number i enter(which is always different). i hope i can be understood and i really appreciate any help.

      PeterJones 1 Reply Last reply Reply Quote 0
      • PeterJones
        PeterJones @Ruben Lara last edited by

        @Ruben-Lara ,

        I might have understood. Here is my suggestion for a PythonScript solution:

        # encoding=utf-8
        """in response to https://community.notepad-plus-plus.org/topic/20991/find-and-replace-automation-in-python
        """
        from Npp import *
        
        editor.beginUndoAction()
        
        r = int( notepad.prompt("number", "Replace starting at", 1) )
        
        for s in range(1,19):
            srch = "{:04d}".format(s)   # you showed 4-digit leading zeros
            repl = "{:04d}".format(r)   # assumed replacement also 4-digit leading zeros
            #console.write("s/{}/{}/\r\n".format(srch,repl))    # for debugging
            editor.replace(srch,repl)   # do the replacement on the first match found
            r = r + 1                   # move to next replacement integer
        
        editor.endUndoAction()  # allows a single undo to undo all 18 replacements
        
        1 Reply Last reply Reply Quote 5
        • Ruben Lara
          Ruben Lara last edited by

          Peter, you are a legend, that is exactly what I needed, Thank you so much !!!

          1 Reply Last reply Reply Quote 2
          • First post
            Last post
          Copyright © 2014 NodeBB Forums | Contributors