I have a text file that has over 60,000 lines in it and I need to go through and find a specific word and then multiply the number after it. For example:
The cat jumped over the log
tree 6
the dog also jumped over the log
tree 43
Would end up, if multiplying by 2, as:
The cat jumped over the log
tree 12
the dog also jumped over the log
tree 86
I know this is fairly simple to do but I can't wrap my head around it. I need to step through the whole text file word by word looking for instances of "tree ", finding the integer after this, making the change, and then replacing the line.
I also know that every occurrence of "tree " will always have an integer next to it.
Thanks for your help.
Edit:
Current code I have as of now is:
file = open('export_desc.txt', 'r')
a = "ext_mpl "
for line in file:
n = file.find(a+1)
n = n*2
file.write(line.replace(a+1, a+n))
file.close()
You don't even have to write a python script, a sed
command can help you:
sed -r '/^tree ([0-9]+)$/{h;s/^.* ([0-9]+)$/echo \1*2|bc/e;H;g;s/[0-9]+\n//}' export_desc.txt
Sample:
>sed -r '/^tree ([0-9]+)$/{h;s/^.* ([0-9]+)$/echo \1*2|bc/e;H;g;s/[0-9]+\n//}' 123
The cat jumped over the log
tree 12
the dog also jumped over the log
tree 86
>cat 123
The cat jumped over the log
tree 6
the dog also jumped over the log
tree 43
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments