Search code examples
xmlperlshellxml-libxml

Replace a tag and value in xml using perl one liner


I need to replace the date value 2016-11-02 in the date tag with a new value using a perl one liner

<header>
            <name>V5 CDS Composites</name>
            <version>1.1a</version>
            <date>2016-11-02</date>

    </header>

I can do this using xml libxml but want to do this in the shortest possible way using a perl one liner. I cannot use just 2016-11-02 as there are multiple instances of this with different tags.

I am doing this inside a shell where the tag and the value are inside a variable


Solution

  • Try the following one liner

    perl -pe 'my $new_date = "2016-12-12"; s/<date>.+/<date>$new_date<\/date>/g' xml.txt
    

    Here

    -p use to iterate the loop on a file and the line gets print after that.
    
    -e for execute the script
    

    And there is another switch use to perform the changes in original file. which is -i . Then you want to make a copy of original file means the oneliner should be

    perl -i.copy -pe 'my $new_date = "2016-12-12"; s/<date>.+/<date>$new_date<\/date>/g' xml.txt
    

    The file will store into .copy extension.