Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading