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

Question:

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.

Asked By: user1551817

||

Answers:

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)
Answered By: balderman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.