I have a file which contains a timestamp:
"buildTimestamp": "2021-07-19T17:00:00Z"
I want to replace it with the current build time, using a one-line command.
date | xargs -I {} perl -pi -e 's/2021-07-19T17:00:00Z/"$0"/g' serviceProperties.json
But it's not working as expected. Any suggestions?
CodePudding user response:
You should really be using a JSON parser to handle JSON data. jq can do this job.
If your file looks like
{
"foo": {
"bar": {
"buildTimestamp": "2021-07-19T17:00:00Z"
}
}
}
Then
jq '.foo.bar.buildTimestamp = (now | strftime("%FT%TZ"))' serviceProperties.json
outputs this on Feb 24, 2022 at 16:36:15 America/New_York
{
"foo": {
"bar": {
"buildTimestamp": "2022-02-24T21:36:15Z"
}
}
}
CodePudding user response:
Assuming data in serviceProperties.json
[
{
"buildTimestamp": "2021-07-19T17:00:00Z"
},
{
"buildTimestamp": "2021-07-19T17:00:00Z"
},
{
"buildTimestamp": "2021-07-19T17:00:00Z"
},
{
"buildTimestamp": "2021-07-19T17:00:00Z"
}
]
After running date %FT%TZ | xargs -I % perl -pi -e 's/2021-07-19T17:00:00Z/%/g' serviceProperties.json
serviceProperties.json will be
[
{
"buildTimestamp": "2022-02-25T03:30:20Z"
},
{
"buildTimestamp": "2022-02-25T03:30:20Z"
},
{
"buildTimestamp": "2022-02-25T03:30:20Z"
},
{
"buildTimestamp": "2022-02-25T03:30:20Z"
}
]
As you are replacing with $0 it will take arguments from perl command and hence you will have unexpected results. Instead replacing with a helper using xargs will do the trick.
To learn more about how xargs is working in this case read here
CodePudding user response:
perl -pi -e 's/2021-07-19T17:00:00Z/'"$(date)"'/g' serviceProperties.json