crankshaft
crankshaft

Reputation: 2677

python string replace unknown number

I am a beginner with PYTHON and useless with regex and are struggling to replace an unknown number in a file with a new number. I have looked through the python how tos and examples for re but still can't make any progress on how to create the expression.

# myfile.txt
Some text
More text
Option  "BlankTime" "15"
more text

I want to replace "15" with another number, this line only appears once in the file, but the line number it is on is unknown, and the value of 15 is also unknown and could be any number contained in the quotation marks.

Best way would be to do it with python ( re ?? ) but if that can't be done then maybe sed ??

Upvotes: 0

Views: 1847

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336498

import re
with open("myfile.txt", "r") as myfile:
    mytext = myfile.read()
pattern = re.compile(r'^(Option\s+"BlankTime"\s+")(\d+)"', re.MULTILINE)
mystr = pattern.sub(r'\1REPLACED"', mytext)
with open("myfile.txt", "w") as myfile:
    myfile.write(mytext)

This will replace all occurrences in the file at once. I've put the number into capturing parentheses in case you'd want to do something with it before the replacement.

Upvotes: 1

NPE
NPE

Reputation: 500963

It sounds like you're looking for a particular parameter (BlankTime). This can be done with the following sed one-liner:

cat myfile.txt | sed 's/\("BlankTime"\s*"\)[^"]*/\1987/'

This'll search for "BlankTime" and replace its value with 987, leaving all the other lines intact.

edit To replace the contents of the file, use the following two-step approach:

cat myfile.txt | sed 's/\("BlankTime"\s*"\)[^"]*/\1987/' > myfile.txt.tmp
mv myfile.txt.tmp myfile.txt

Upvotes: 1

j0057
j0057

Reputation: 922

myfile = open('myfile.txt', 'r')
text = myfile.read()
myfile.close()

print re.sub(r'\d+', '42', text)

\d matches a number, + matches at least one occurrence of the preceding pattern.

Upvotes: -1

Related Questions