0

I'd like to be able to replace a certain string text in a .txt file that is open in Notepad ++ but using more than the simple text replacement. I need a query to search for a string that starts with:

# Model Data Entry xxx

and then to replace anything on the same line with:

# Model Data Entry yyy

whereby xxx is any random number and whereby yyy would be starting from 0 and ascending in numerical order replacing the text at the first instance in the file going up a value of 1 for each of the entries that follow. Example:

Original text:

# Model Data Entry 69
# Model Data Entry 119
# Model Data Entry 3
# Model Data Entry 71
# Model Data Entry 45

processed text:

# Model Data Entry 0
# Model Data Entry 1
# Model Data Entry 2
# Model Data Entry 3
# Model Data Entry 4...

It should be noted that there will be several lines of other text in between all the instances of # Model Data Entry

2 Answers 2

2

You can run a python script within the PythonScript plugin.

If it is not yet installed, follow this guide

Create a script (Plugins >> PythonScript >> New Script)

Copy this code and save the file (for example calculate.py):

import re

counter = -1
def calculate(match):
    global counter
    counter += 1
    return ' ' + str(counter)

editor.rereplace('(?<=# Model Data Entry)\h*\d*', calculate)
  • Open the file you want to change
  • Run the script (Plugins >> PythonScript >> Scripts >> calculate)
  • Done

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

6
  • Wow this looks like exactly what I am looking for . I will test this shortly. Sep 14, 2020 at 18:02
  • +1 Your solution is definitely more efficient. TIL you can use Notepad++ to run python. Sep 14, 2020 at 18:18
  • Ok it seems to work ok except that if there are no numbers after # Model Data Entry then it skips the entry. I still need it to add numbers to # Model Data Entry that have no numbers following it Sep 14, 2020 at 18:44
  • @KalamalkaKid: See my edit.
    – Toto
    Sep 14, 2020 at 19:07
  • amazing.. THANK YOU !!! Sep 14, 2020 at 19:09
0

This Kind of replacement is very hard without using Scripting languages, as @Toto shown an example of using Python. An example of native windows Powershell:

$i=0;(gc "Filepath")|%{if($_ -match "^# Model Data entry.*"){$_ -replace "^#\sModel\sData\sEntry\s\d+$","# Model Data entry $($i)";$i++}else{$_}}|Set-Content "Filepath"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.