while True:
flag=0
error=""
try:
word=input()
while word:
com=input().split()
if("replace" in com[0]):
for i in range(0,len(word)+1):
word=word.replace(com[1],com[2])
elif("remove" in com[0]):
word=word.replace(com[1],'')
elif("addhead" in com[0]):
word=com[1]+word
elif("addtail" in com[0]):
word=word+com[1]
else:
if("end" not in com[0]):
flag=1
error=com[0]
else:
if flag==1:
print("invalid command "+error)
word=""
continue
else:
print(word)
word=""
continue
except EOFError:
pass