Reputation: 199
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
Upvotes: 0
Views: 846
Reputation: 53478
Use perl
and an XML aware tool:
perl -MXML::Twig -0777 -e '$t=XML::Twig->parse(<>);$_->set_text('2017-01-01') for $t ->get_xpath('.//date');$t->print'
Or perhaps:
perl -MXML::Twig -0777 -e 'XML::Twig->new(twig_handlers=>{date=>sub{$_->set_text("2017-01-01")}})->parse(<>)->print'
(Slightly shorter, depends if that's easier to read or not).
It's technically slightly longer than some of the alternatives here, but it has the benefit of being an actual XML parsed solution.
You could also use parsefile_inplace
instead, to use it 'sed like' on a file. You might also find setting pretty_print
to be useful, to reformat the XML.
Upvotes: 2
Reputation: 91385
This one liner do the job and save the file before doing the substituion
perl -pi.back -e 's~(?=<date>)[\d-]+(?=</date>)~2016-11-18~' file.xml
Upvotes: 1
Reputation: 5927
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.
Upvotes: 1