Bash Question

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

<name>V5 CDS Composites</name>


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

Answer Source

Try the following one liner

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


-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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download