Chris Jefferson
Chris Jefferson

Reputation: 7157

Increment all numbers in a file

I have a file which looks like:

(890 1782 0)
(8 9 56)(5 28 987)

And I want to increment every number by one:

(891 1783 1)
(9 10 57)(6 29 988)

I am sure there must be a simple way of doing this, but I can't figure it out. Happy with any language (bash/awk/perl/python)

Upvotes: 2

Views: 959

Answers (2)

alecxe
alecxe

Reputation: 473873

You can find all numbers by using \d+ regular expression, use re.sub() and pass a function to as a repl argument. For modifying a file in place, you can use fileinput:

import fileinput
import re

pattern = re.compile('\d+')
for line in fileinput.input('input.txt', inplace=True):
    if line:
        print(pattern.sub(lambda m: str(int(m.group(0)) + 1), line), end='')

Example (using a string instead of a file):

>>> import re
>>> s = "(891 1783 1)"
>>> pattern = re.compile('\d+')
>>> pattern.sub(lambda m: str(int(m.group(0)) + 1), s)
'(892 1784 2)' 

Upvotes: 4

Vytenis Bivainis
Vytenis Bivainis

Reputation: 2376

My solution:

numbers=$(egrep -o "[0-9]+" input.txt | xargs printf "%d + 1\n"  | bc)
printf "$(cat input.txt  | sed -r 's/[0-9]+/%d/g')\n" $numbers

Upvotes: 0

Related Questions