簡體   English   中英

將匹配的正則表達式的一部分替換為 sed

[英]Replace part of a matched regex with sed

我有一個示例文本,它是一個數據庫 output:

對象/blabla | 恢復 | 手冊 | 還原失敗:卷不希望存在 | 備份失敗 | 2020-10-06 T 21:39:01 | 2020-10-06 T 21:39:01 | 0 | 0 | 0 > | 0 | 0

只需要將時間/日期字符串中的“T”更改為“,”(逗號)。

到目前為止,我已經嘗試過:

sed -e 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}/g' -e 's/T/,/g'

但它無法僅隔離日期時間字符串,並生成以下 output:

對象/blabla | 恢復 | 手冊 | 恢復失敗:,卷不想存在 | 備份失敗 | 2020-10- 06,21:39:01 | 2020-10-06,21:39:01 | 0 | 0 | 0 > | 0

因此,它也將“The”更改為“,he”,這是不需要的。

您不需要匹配完整的日期時間字符串。 以下 sed 應該適合你:

sed -E 's/([0-9]{2})T([0-9]{2})/\1,\2/g' file
objs/blabla | Restore | manual | Restore Failed: The volume does not want to exist | BackupFailed | 2020-10-06,21:39:01 | 2020-10-06,21:39:01 | 0 | 0 | 0 > | 0 | 0

細節:

  • ([0-9]{2}) - 這里我們匹配T前后的 2 個數字,並將它們捕獲到組 #1 和 #2 中
  • \1,\2 :我們將捕獲的值放回原位,替換T

根據 OP 下面的評論,更細粒度的正則表達式有效:

sed -E 's/([0-9]{4}(-[0-9]{2}){2})T([0-9]{2}(:[0-9]{2}){2})/\1,\3/g' file

使用 GNU awk gensub選項,請嘗試以下操作。

awk -v regex="([0-9]{2})T([0-9]{2})" '{$0=gensub(regex,"\\1,\\2", "g", $0)} 1' Input_file

說明:為上文添加詳細說明。

awk -v regex="([0-9]{2})T([0-9]{2})" '   ##Starting awk program from here, mentioning regex here to match 2 digits T 2 digits.
{
  $0=gensub(regex,"\\1,\\2", "g", $0)    ##using gensub to match the regex in current line and substitute 1st and 2nd matched part with comma globally in current line and save it into current line itself.
}
1                                        ##Mentioning 1 will print edited/non-edited line here.
' Input_file                             ##Mentioning Input_file name here.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM