costica_p
costica_p

Reputation: 51

replace string with regex in lua

I have many log files, each containing 1000+ lines. One part of file is below:

{@BLOCK|1%r1331|00
{@A-JUM|0|-9.352000E+06{@LIM2|+9.999999E+99|+1.000000E+04}}
}
{@BLOCK|1%x1001_swp|00
{@A-JUM|0|+3.362121E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x1101_swp|00
{@A-JUM|0|+3.282704E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x201_swp|00
{@A-JUM|0|+3.276452E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x202_swp|00
{@A-JUM|0|+3.216571E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}

I want to replace "+3.282704E+00" (8-th row) with another value. Is important to know, every tag like "{@BLOCK|1%x1101_swp|00" is unique, but line number for this tag may be different for different files. How can realize this in Lua? I tryed to use regex for both lines, between "@BLOCK" and "{@LIM2" but with no results. For:

 {@BLOCK|1%x1101_swp|00
 {@A-JUM|0|+3.282704E+00{@LIM2|+2.000000E+01|+0.000000E+00}}

I tryed:

if string.match(line,"{@BLOCK%|1%%1101_swp%|00..{@A-JUM%|0%|.............{@LIM2") then
string.gsub(line,"{@A-JUM%|0%|.............{@LIM2", "{@A-JUM%|0%|"..ff[#lines].."{@LIM2")

Upvotes: 2

Views: 2069

Answers (2)

Mike V.
Mike V.

Reputation: 2215

You can use this more unified way:

local line = [[{@BLOCK|1%r1331|00
{@A-JUM|0|-9.352000E+06{@LIM2|+9.999999E+99|+1.000000E+04}}
}
{@BLOCK|1%x1001_swp|00
{@A-JUM|0|+3.362121E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x1101_swp|00
{@A-JUM|0|+3.282704E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x201_swp|00
{@A-JUM|0|+3.276452E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x202_swp|00
{@A-JUM|0|+3.216571E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}]]

local function Replace(line, unic_block, unic_num, to_num)
    unic_block = unic_block:gsub("%%","%%%%") -- escaping magic symbol '%'
    unic_num = unic_num:gsub("[%+%.]",function(c) return "%"..c end)  -- escaping magic symbols '+' and '.'
    return line:gsub("(" ..unic_block .. ".-%c+.-)" .. unic_num, "%1" .. to_num ) 
end
local xline = Replace(line, "{@BLOCK|1%x1101_swp|00", "+3.282704E+00", "9999999")

print (xline)

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

You may use

local res = line:gsub("(%{@BLOCK%|1%%x201_swp%|00\r?\n%{@A%-JUM%|0%|).-(%{@LIM2%|)", "%1".. ff[$lines] .."%2")

See the Lua demo

Details

  • (%{@BLOCK%|1%%x201_swp%|00\r?\n%{@A%-JUM%|0%|) - Group 1: {@BLOCK|1%x201_swp|00 substring, followed with an optional CR symbol, then LF, and then {@A-JUM|0|
  • .- - any 0+ chars, as few as possible
  • (%{@LIM2%|) - Group 2: {@LIM2| substring.

The %1 and %2 placeholders refer to the values stored in Groups 1 and 2 respectively from the replacement pattern.

Upvotes: 1

Related Questions