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>You've tagged it <code>perl</code> so here's how I'd do it:</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;

use XML::Twig;
#iterate the files. 
foreach my $xml_file ( glob "*.xml" ) { 
    #regex match the number for the XML. 
    my ( $file_num ) = $xml_file =~ m/(\d+).xml/; 
    #create an XML::Twig, and set it to 'indented' output. 
    XML::Twig -&gt; new ( pretty_print =&gt; 'indented',
          #matches elements and runs the subroutine on 'it'. ($_) is the 
          #current element in this context. 
                       twig_handlers =&gt; { 'address/id' =&gt; sub { $_ -&gt; set_text($file_num) }, 
                                          'count'      =&gt; sub { $_ -&gt; set_text($file_num) },  
           #parsefile_inplace reads and writes back any changes to the file
           #as it goes. 
                                        } ) -&gt; parsefile_inplace($xml_file); 


}
</code></pre>

<p>This uses <code>XML::Twig</code>, which allows you do an in place edit. It does this via the element handlers, which upon hitting a suitable match, replaces the content with the right numeric value for the file.</p>

<p>I've opted to replace the defined content for <code>address/id</code> and <code>count</code>, rather than just doing straight search and replace, because then ... you don't have to worry about <code>1000</code> showing up anywhere else in the content. (Like the address). </p>

python bash perl