替换具有 xml 的 txt 文件中的日期

Replace date in a txt file having xml

我有一个文本文件,其中包含 xml 数据。现在我想用 dd/mm/yyyy 格式替换当前日期加上 2 天的日期。我试过它会在 Unix 中使用 sed 命令,但我无法做到这一点。在命令下方我试图更改日期。但它没有更改文本。

sed -i 's/\<Date\>*\<Date\>/\<Date\>date +"%m/%d/%y"<Date\>/g' avltest.xml

<Args>
     <Date>01/10/2017</Date>
<\Args>

日期字段中,我想在我运行我的命令或我可以从脚本使用该命令时更改日期。

这是一个 perl 版本:

perl -MPOSIX=strftime -i -pe 's{<Date>.*?</Date>}{"<Date>" . strftime("%m/%d/%Y", localtime(time + 2 * 24 * 60 * 60)) . "</Date>"}e' avltest.xml

我删除了 <> 之前多余的反斜杠,在 </Date> 中添加了缺少的 /,并修复了 * 部分。

不要使用正则表达式修饰XML。 It's dirty, hacky, brittle and unnecessary:

#!/usr/bin/perl
use warnings;
use strict;

use XML::Twig;
use Time::Piece;

#load your file
my $twig = XML::Twig->new->parsefile('avltest.xml');

#iterate all <Date> elements. 
foreach my $date_elt ( $twig->get_xpath('//Date') ) {
   my $date = localtime;
   #increment it by two days. 
   $date += 2 * 60 * 60 * 24; #two days. 
   #replace it. 
   $date_elt -> set_text($date -> strftime("%m/%d/%Y"));       
}

#print XML to STDOUT. 
$twig -> set_pretty_print('indented_a');
$twig -> print;

这将按照您的描述执行您想要的操作,而不会被 'end of year/end of month' 绊倒。

如果您愿意,可以在 XML twig 中使用 parsefile_inplace - 这需要稍微不同的代码设置。