Replace characters in a string from a list and create a copy for each
<p>I'm not sure if it's even possible to do what I need with sed.</p>

<p>I want to be able to replace a string in a file with another string from a list and create a separate copy for each version.</p>

<p>For example, the original file has:</p>

<pre><code>apple dog orange
</code></pre>

<p>I want to replace <code>dog</code> with a list of different words. i.e cat, rabbit, duck.
This would create copies of the original file, each with a different change.</p>

<p>File1.txt (the original file) - <code>apple dog orange</code>
File2.txt - <code>apple cat orange</code>
File3.txt - <code>apple rabbit orange</code>
File4.txt - <code>apple duck orange</code></p>

<p>I've been able to use Sed to find and replace a single file:</p>

<pre><code>sed -i '' 's/dog/cat/g' *.html
</code></pre>

<p>I need a way to replace from a list though, and create a unique copy of each.</p>

<p>I'm on OSX. As I said before, sed might not be the tool to use here, maybe Python? I'm open to any suggestions to do this.</p>

<p>Thanks</p>

<p>You could do it with python using regex.</p>

<pre><code>import re
import os

filename = '/path/to/filename.txt'
with open(filename, 'r') as f:
    text = f.read()

names = ['cat', 'rabbit', 'duck']
for i, name in enumerate(names):
    new_text = re.sub(r'dog', name, text)
    base, ext = os.path.splitext(filename)
    with open('{}_{}{}'.format(base, i, ext), 'w') as f:
        f.write(new_text)
</code></pre>

python string replace sed