How to use Global Replace to number each line

Posted by Nick Gammon on Thu 29 Dec 2005 07:40 PM — 2 posts, 7,712 views.

Australia Forum Administrator #0
Another use for the Notepad's Global Replace functionality is to do something like number each line sequentially. Here is how you could do that:


Find Pattern: ^.*$
Replacement: f
Line by Line: checked
Script:

count = 0

function f (str)
  count = count + 1
  return string.format ("%04i", count) .. ": " .. str
end -- function f


Applying this to a batch of code we can see the difference:


Before replacement:

sub ResetTmr (name, output, wildcards)
  dim Icnm ' Names.
  dim Tms ' Current times.
  dim Ada
  Ada = split(GetVariable("Ada"),",")
  Icnm = split(GetVariable("Icnm"),",")
  Tms = split(GetVariable("Tms"),",")
  dim count,test
  test = 0
  for count = 0 to ubound(Icnm)
    if Icnm(count) = name then
      Tms(count) = 0
      if ada(count) > 0 then
        test = 1
      end if
    end if
  next
  SetVariable "Tms", join(Tms,",")
  if test then
    EnableTrigger "CatchStat", 1
    Send "stats"
  end if
end sub

After replacement:

0001: sub ResetTmr (name, output, wildcards)
0002:   dim Icnm ' Names.
0003:   dim Tms ' Current times.
0004:   dim Ada
0005:   Ada = split(GetVariable("Ada"),",")
0006:   Icnm = split(GetVariable("Icnm"),",")
0007:   Tms = split(GetVariable("Tms"),",")
0008:   dim count,test
0009:   test = 0
0010:   for count = 0 to ubound(Icnm)
0011:     if Icnm(count) = name then
0012:       Tms(count) = 0
0013:       if ada(count) > 0 then
0014:         test = 1
0015:       end if
0016:     end if
0017:   next
0018:   SetVariable "Tms", join(Tms,",")
0019:   if test then
0020:     EnableTrigger "CatchStat", 1
0021:     Send "stats"
0022:   end if
0023: end sub


Of course, you can omit the leading zeroes by changing the string.format line, changing "%04i" to "%4i".
Australia Forum Administrator #1
You can reverse the process by searching for numbers at the start of the line and omitting them, like this:


Find Pattern: ^[%d]+: (.*)$
Replacement: %1
Line by Line: checked