user1551817
user1551817

Reputation: 7451

How to replace a number in a text file using regular expressions

I have a text document with lots of lines that look something like this:

some_string_of_changing_length 1234.56000000 99997.65723122992939764 4.63700 text -d NAME -r

I want to go line by line and change only the 4th entry (the number 4.63700 in this example) and replace it with another number.

I think I have to do with using regular expressions, but I'm not sure how to ask to replace the 4th entry only.

I would be happy to do this in either python or bash - whatever is easiest.

Upvotes: 0

Views: 48

Answers (1)

balderman
balderman

Reputation: 23815

If you know the offset - the below will work for you (so there is no need for regex)

line = 'some_string_of_changing_length 1234.56000000 99997.65723122992939764 4.63700 text -d NAME -r'
new_val = 'I am the new val'
parts = line.split(' ')
parts[3] = new_val
line = ' '.join(parts)
print(line)

Upvotes: 1

Related Questions