一直把我的頭撞到墻上,但基本上我有一個 curl 命令,它包含一個替換(sed)命令,我想將它轉換為等效于使用替換的 powershell,我覺得我的引號/轉義順序文字不太對。
我的輸出是這樣的:"cattle.io/timestamp":"2022-02-22T11:11:00Z"
我想要更改的唯一部分是日期/時間戳,以便它更新為當前日期時間。
以下適用于 curl: sed "s/\"cattle\.io\/timestamp\"\:\"[0-9T:Z-]*\"/\"cattle\.io\/timestamp\":\"(date -u "%Y-%m-%dT%H:%M:%SZ")"/g"
我認為它會是這樣的:replace '"cattle.io/timestamp":"[0-9T:Z-]*"','"cattle.io/timestamp":"(date -uformat "%Y-%m-%dT%H:%M:%SZ")'使用單引號來轉義,但顯然不是。
uj5u.com熱心網友回復:
您可以使用
$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"
在您的代碼中:
$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"
輸出:
"cattle.io/timestamp":"2022-02-23T11:07:56Z"
詳情:
-replace是在 Powershell 中支持基于正則運算式的搜索和替換的運算子("cattle\.io/timestamp":")- 捕獲$1與文字文本匹配的組 1 ( )"cattle.io/timestamp":"(注意文字點需要在正則運算式中轉義)[\dTZ:-]*- 匹配零個或多個數字T、、、Z或字符:-(")"- 捕獲與字符匹配的組 2"`${1}$(date -uformat "%Y-%m-%dT%H:%M:%SZ")`$2"是表示雙引號字串文字(因此允許字串插值)的替換,它-replace用 Group 1 值替換找到的每個匹配項(參見對"`${1}"Group 1 的數字反向參考,之前的反引號$告訴 Powershell 這不是插值變數,并且大括號是必需的,因為下一個字符將是數字字符) 日期(它需要$(...)語法),然后是第 2 組值(`"如果您不想在模式中引入另一個捕獲組,則可以只使用 a 代替)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434762.html
