DevCybran DevCybran -4 years ago 90
Perl Question

Using perl for incrementing numbers in text file

I want to batch-process text files from the command line by adding a static offset to all numbers contained in said files using perl.

For example, if the file contained the line:

AN_IDENTIFIER_TOKEN = 1,
and the offset is
19
then this line should be transformed to
AN_IDENTIFIER_TOKEN = 20,


I tried to use
perl -pe 's/(\d+)$/19+$1/e' file1.txt
but that did produce the same output as input (no numbers were changed). What is the correct command to pass to perl?

Using ActiveState Perl 5.24.1 on Windows.

Answer Source

It should work, try this:

perl -pe "s/(\d+)/19+$1/eg" file1.txt

Your regex (\d+)$ matched only digits at the end of a string, so that won't match 1,

If you want to match only " = <digits>,", then use something like this

perl -pe "s/ = (\d+),/' = '.(19+$1).','/eg" file1.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download