Rename a particular instance in multiple files with the file name?
<p>I had to create about 500 copies of a xml file in the directory, which I managed to get done. As a part of the next problem is that I want to rename particular text in the file. How can I go about doing it?</p>

<p>This is what I have:
1000.xml, 1001.xml, 1002.xml...</p>

<p>1000.xml:</p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation='test.xsd'&gt;
&lt;address&gt;
    &lt;name&gt;Joe Tester&lt;/name&gt;
    &lt;street&gt;Baker street 5&lt;/street&gt;
    &lt;id&gt;1000&lt;/id&gt;
&lt;/address&gt;
&lt;count&gt;1000&lt;/count&gt;
</code></pre>

<p></p>

<p>Essentially, this is copied to all the other files, but with a numerical and chronological name. How do I replace this "1000" with the "file name"? So, the new file should be -
1001.xml:</p>

<pre><code>    &lt;?xml version="1.0" encoding="UTF-8"?&gt;
    &lt;addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:noNamespaceSchemaLocation='test.xsd'&gt;
    &lt;address&gt;
        &lt;name&gt;Joe Tester&lt;/name&gt;
        &lt;street&gt;Baker street 5&lt;/street&gt;
        &lt;id&gt;1001&lt;/id&gt;
    &lt;/address&gt;
    &lt;count&gt;1001&lt;/count&gt;
&lt;/addresses&gt;
</code></pre>

<p>I could do only this - <code>sed -i '' -e 's/1000/1001/g' $(find . -type f)</code> which will replace all the 1000 with 1001, but not the file name.</p>

<p>After deciphering your question I see you want to change actual content in the xml file i.e the id or some other node's text to the name of the file so use an xml parser like <a href="http://lxml.de/" rel="nofollow"><em>lxml</em></a></p>

<pre><code>from  glob import iglob
import lxml.etree as et

for fle in iglob("[0-9][0-9][0-9][0-9].xml"):
    tree = et.parse(fle)
    id_ = tree.find(".//id").text = fle
    tree.write(fle, encoding="utf-8")
</code></pre>

<p>If you want to change the count also use:</p>

<pre><code> for fle in iglob("[0-9][0-9][0-9][0-9].xml"):
        tree = et.parse(fle)
        id_, count = tree.find(".//id"), tree.find(".//count")
        id_.text = count.text = fle
        tree.write(fle, encoding="utf-8")
</code></pre>

<p>Whatever text you want to set to the file name just look for the node with find and set the text use the <em>node.text = ...</em> logic. If you want to use the name ignoring the extension just split:</p>

<pre><code>for fle in iglob("[0-9][0-9][0-9][0-9].xml"):
        tree = et.parse(fle)
        id_, count = tree.find(".//id"), tree.find(".//count")
        id_.text = count.text = fle.split(".")[0]
        tree.write(fle, encoding="utf-8")
</code></pre>

python bash perl