• Login
Community
  • Login

find and replace automation in python

Scheduled Pinned Locked Moved Help wanted · · · – – – · · ·
3 Posts 2 Posters 439 Views
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.
  • R
    Ruben Lara
    last edited by Apr 5, 2021, 12:56 PM

    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.

    P 1 Reply Last reply Apr 5, 2021, 1:23 PM Reply Quote 0
    • P
      PeterJones @Ruben Lara
      last edited by Apr 5, 2021, 1:23 PM

      @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
      • R
        Ruben Lara
        last edited by Apr 10, 2021, 5:00 AM

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

        1 Reply Last reply Reply Quote 2
        2 out of 3
        • First post
          2/3
          Last post
        The Community of users of the Notepad++ text editor.
        Powered by NodeBB | Contributors