Question

I'm trying to learn how to evaluate (i.e. perform actual mathematical calculations) in regex replacements.

I've got a file test.txt which contains:

|R 1:27_2-6-02
I 1656 misc:IN 1 2200 1470 0 1 '
C 1655 2 1 0C 1659 2 2 0

From the command line (in Windows) I'm running the following:

perl -i.bak -pe "s!(I.*?)(misc:IN 1 )(\d+)(.*?')!${1}misc:OUT 2 ${3}/10${4}!e" test.txt

I'm expecting the result to have "misc:IN 1 " replaced by "misc:OUT 2 " and for it to be followed by 220, not 2200. However, this is not working.

I've looked at the tutorial here, which shows the following example where there is a mathematical calculation performed during the regex substition:

# convert percentage to decimal
$x = "A 39% hit rate";
$x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"
Was it helpful?

Solution

The RHS must be fully valid perl code to be evalled. You need to define and concatenate strings.

perl -i.bak -pe "s!(I.*?)(misc:IN 1 )(\d+)(.*?')!qq{${1}misc:OUT 2 } . ${3}/10 . qq{${4}}!e" test.txt

Also note the use of qq{} for strings since "" is used on the command line to enclose the perl code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top