Home > OS >  How to replace a number in a text file using regular expressions
How to replace a number in a text file using regular expressions

Time:11-17

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.

CodePudding user response:

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)
  • Related