Using fileinput.input() you can easily and safely overwrite the input file without explicitly using a secondary file and then overwriting the original file:
import fileinput
extra_line = 'new line here...'
seen_yum = False
f = fileinput.input('test.txt', inplace=True)
for line in f:
if line.startswith('$ yum'):
seen_yum = True
elif line.startswith('$') and seen_yum:
print extra_line
print line,
f.close()
For the input:
some other lines
of no interest to us
$ yum -- to install package
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
$cat -- to read contents of a file
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
the output would be:
some other lines
of no interest to us
$ yum -- to install package
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
new line here...
$cat -- to read contents of a file
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
It's not clear from your question whether the extra line should be inserted before every subsequent line that starts with $ - as the code above does. If you only want one extra line inserted for every $ yum seen you can reset the seen_yum flag.
import fileinput
extra_line = 'new line here...'
seen_yum = False
f = fileinput.input('test.txt', inplace=True)
for line in f:
if line.startswith('$ yum'):
seen_yum = True
elif line.startswith('$') and seen_yum:
seen_yum = False
print extra_line
print line,
f.close()
So if the file contains multiple lines that start with $ yum, and there is a following line that begins with $, a new line will be inserted.