I have below json content in a json file and "pos" value in below json is a variable and need to replace it with a constant like NNNN.
{"qual_table": "TKGGU1.TCUSTORD", "op_type": "INSERT", "op_ts": "YYYY-MM-DDTHH:MI:SS.FFFFFFZ", "pos": "G-AAAAAJcRAAAAAAAAAAAAAAAAAAAHAAoAAA==10687850.2.31.996", "xid": "0.2.31.996", "after": {"CUST_CODE": "BILL", "ORDER_DATE": "YYYY-MM-DD:HH:MI:SS", "PRODUCT_CODE": "CAR", "ORDER_ID": 765, "PRODUCT_PRICE": 1500000, "PRODUCT_AMOUNT": 3, "TRANSACTION_ID": 100}}
I tried perl -i -pe 's/[A-Z]-[A-Z]*\.==*/ NNNN/g' filename.json
but this is not working.
Could you suggest me a regular expression for this. Pls note this is a variable and have different length everytime.
CodePudding user response:
perl -pe 's/"pos"\s*:\s*"\K[^"]*/NNNN/g' filename.json
should work for any length of pos
as long as there is no quote character or newline in the string.
As Shawn pointed out it'd be better to use a json-manipulating tool instead of a string-manipulating one. Otherwise you'll have to rely on assumptions.
CodePudding user response:
jq
is the de-facto standard tool for working with JSON from scripts and the command line. It makes updating a field of an object with a new value trivial:
$ jq '.pos = "NNNN"' input.json
{
"qual_table": "TKGGU1.TCUSTORD",
"op_type": "INSERT",
"op_ts": "YYYY-MM-DDTHH:MI:SS.FFFFFFZ",
"pos": "NNNN",
"xid": "0.2.31.996",
"after": {
"CUST_CODE": "BILL",
"ORDER_DATE": "YYYY-MM-DD:HH:MI:SS",
"PRODUCT_CODE": "CAR",
"ORDER_ID": 765,
"PRODUCT_PRICE": 1500000,
"PRODUCT_AMOUNT": 3,
"TRANSACTION_ID": 100
}
}
(Note that when standard output is a pipe or file or something other than a terminal, the JSON is printed in compact form on a single line.)
The equivalent perl one(ish)-liner would be something like
perl -MJSON::MaybeXS -MFile::Slurper=read_text -E '
my $json = JSON::MaybeXS->new;
my $obj = $json->decode(read_text($ARGV[0]));
$obj->{pos} = "NNNN";
say $json->encode($obj);' input.json
(Adjust as needed for your preferred JSON and file-reading modules)