简体   繁体   中英

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

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.

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.

这一位班轮做这项工作并在进行替代之前保存文件

perl -pi.back -e 's~(?=<date>)[\d-]+(?=</date>)~2016-11-18~' file.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM