简体   繁体   English

用正则表达式在 Bash 或 Perl 中定义一个变量

[英]Define a variable in Bash or Perl with regular expression

I have a file that has some lines like this:我有一个文件,其中有一些这样的行:

{"v":0,"_id":"54ff561168a","time":"1421165205"}

I want to use bash that read each line and set the value of the time as Variable (t) and replace it with other timestamp using date -d @{$t}我想使用 bash 读取每一行并将时间值设置为Variable (t) 并使用date -d @{$t}将其替换为其他时间戳

Do you know how can I use regular expression for getting the value of time as variable?您知道如何使用正则表达式将时间值作为变量获取吗?

That is JSON .那就是JSON You can parse JSON in perl like so:你可以像这样在 perl 中解析 JSON:

#!/usr/bin/perl 
use strict;
use warnings;
use JSON;
use Data::Dumper; 

my $text = '{"v":0,"_id":"54ff561168a","time":"1421165205"}';

my $data = decode_json ( $text );
print Dumper $data;

print $data -> {"time"},"\n";

$data -> {"time"} = time();

$text = encode_json($data);

print "Result:\n";
print $text;

You don't need regular expressions - and indeed, you should actively avoid them, because JSON allows you to format your data with eg line feeds/indentation - and is semantically identical.您不需要正则表达式 - 实际上,您应该主动避免它们,因为JSON允许您使用换行符/缩进等格式化数据 - 并且在语义上是相同的。

Eg you could output your example above as:例如,您可以将上面的示例输出为:

{
   "_id" : "54ff561168a",
   "time" : 1433859139,
   "v" : 0
}

By using:通过使用:

$text = to_json($data, {pretty => 1});

It means the same thing, but different regular expressions apply thanks to changing whitespace etc.这意味着同样的事情,但由于更改了空格等,不同的正则表达式适用。

If you wish to manipulate/reformat your timestamp, I'll refer you to the excellent Time::Piece module:如果你想操作/重新格式化你的时间戳,我会向你推荐优秀的Time::Piece模块:

use Time::Piece;
my $t = localtime ( $data -> {"time"} );
print $t;

Will give:会给:

Tue Jan 13 16:06:45 2015

If you want a specific format:如果你想要一个特定的格式:

print $t->strftime("%Y/%m/%d %H:%M:%S"),"\n";

Giving:给予:

2015/01/13 16:06:45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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