Home > Back-end >  Converting SED to Replace containing Regex and Dates
Converting SED to Replace containing Regex and Dates

Time:02-24

Been slamming my head against the wall on this one but essentially I had a curl command and it contained a replace (sed) command and I would like to convert this to the powershell equivalent of using replace and I feel like my order of quotes/escaping text isn't quite right.

My output would be like so: "cattle.io/timestamp":"2022-02-22T11:11:00Z"

And the only part i would like to change is the date/time stamp so that it updates to the current datetime.

The following works in curl: sed "s/\"cattle\.io\/timestamp\"\:\"[0-9T:Z-]*\"/\"cattle\.io\/timestamp\":\"(date -u "%Y-%m-%dT%H:%M:%SZ")"/g"

I thought it would be something like: replace '"cattle.io/timestamp":"[0-9T:Z-]*"','"cattle.io/timestamp":"(date -uformat "%Y-%m-%dT%H:%M:%SZ")' using single quotes to escape but apparently not.

CodePudding user response:

You can use

$s = '"cattle.io/timestamp":"2022-02-22T11:11:00Z"'
$s -replace '("cattle\.io/timestamp":")[\dTZ:-]*(")',"`${1}$(date -uformat  "%Y-%m-%dT%H:%M:%SZ")`$2"

In your code:

$command = (curl --silent -H "Authorization: Bearer token-xxx" --url 'link.com' -X GET  -H 'Content-Type: application/json' -H 'Cache-Control: no-cache' --insecure 2>&1) -replace '("cattle\.io/timestamp":")[\dTZ:-]*(")',"`${1}$(date -uformat  "%Y-%m-%dT%H:%M:%SZ")`$2"

Output:

"cattle.io/timestamp":"2022-02-23T11:07:56Z"

Details:

  • -replace is the operator that supports regex based search and replace in Powershell
  • ("cattle\.io/timestamp":") - Capturing group 1 ($1) that matches a literal "cattle.io/timestamp":" text (note the literal dot needs to be escaped in regular expressions)
  • [\dTZ:-]* - matches zero or more digits, T, Z, : or - chars
  • (") - Capturing group 2 that matches a " char
  • "`${1}$(date -uformat "%Y-%m-%dT%H:%M:%SZ")`$2" is the replacement that represents a double quoted string literal (and hence allowing string interpolation), that replaces each match found with -replace with Group 1 value (see the "`${1}" numeric backreference to Group 1, the backtick before $ tells Powershell this is not an interpolated variable, and the braces are necessary since the next char will be a numeric char) date (it needs $(...) syntax) and then Group 2 value (you might just use a `" instead if you do not want to introduce another capturing group in the pattern).
  • Related