我有一個檔案如下
"time":"2022-03-01T12:00:25.388Z","duration":0.8255,"error":0
"time":"2022-03-01T12:00:26.809Z","duration":0.29521,"error":0,"state":"pending
"time":"2022-03-01T12:00:29.053Z","duration":2.90688,"error":0,"options":"merge_request.create
"time":"2022-03-01T12:00:00.635Z","duration":0.46049,"error":0
"time":"2022-03-01T12:00:39.351Z","duration":0.76487,"error":0,"state":"failed
我想在末尾添加 " 但只添加到以字串結尾的行
我給了sed -i 's/$/",/' filename,但它在所有行的末尾添加了引號。
所需的輸出是
"time":"2022-03-01T12:00:25.388Z","duration":0.8255,"error":0
"time":"2022-03-01T12:00:26.809Z","duration":0.29521,"error":0,"state":"pending"
"time":"2022-301T12:00:29.053Z","duration":2.90688,"error":0,"push_options":"merge_request.create"
"time":"2022-03-01T12:00:00.635Z","duration":0.46049,"error":0
"time":"2022-03-01T12:00:39.351Z","duration":0.76487,"error":0,"state":"failed"
有沒有辦法做到這一點?
uj5u.com熱心網友回復:
您可以使用
sed 's/:"[^"]*$/&"/' file > tmp && mv tmp file
sed -i 's/:"[^"]*$/&"/' file # GNU sed
's/:"[^"]*$/&"/'命令的意思是:
:"[^"]*$- 匹配一個:"子字串,然后匹配零個或多個字符,"直到字串結尾&""- 用它自己和一個字符替換匹配。
查看在線演示:
#!/bin/bash
s='"time":"2022-03-01T12:00:25.388Z","duration":0.8255,"error":0
"time":"2022-03-01T12:00:26.809Z","duration":0.29521,"error":0,"state":"pending
"time":"2022-03-01T12:00:29.053Z","duration":2.90688,"error":0,"options":"merge_request.create
"time":"2022-03-01T12:00:00.635Z","duration":0.46049,"error":0
"time":"2022-03-01T12:00:39.351Z","duration":0.76487,"error":0,"state":"failed'
sed 's/:"[^"]*$/&"/' <<< "$s"
輸出:
"time":"2022-03-01T12:00:25.388Z","duration":0.8255,"error":0
"time":"2022-03-01T12:00:26.809Z","duration":0.29521,"error":0,"state":"pending"
"time":"2022-03-01T12:00:29.053Z","duration":2.90688,"error":0,"options":"merge_request.create"
"time":"2022-03-01T12:00:00.635Z","duration":0.46049,"error":0
"time":"2022-03-01T12:00:39.351Z","duration":0.76487,"error":0,"state":"failed"
uj5u.com熱心網友回復:
提出awk解決方案:
awk '/[[:alpha:]]$/{$0=$0"\""}1' input.txt
uj5u.com熱心網友回復:
使用sed
$ sed 's/[a-z]$/&"/' input_file
"time":"2022-03-01T12:00:25.388Z","duration":0.8255,"error":0
"time":"2022-03-01T12:00:26.809Z","duration":0.29521,"error":0,"state":"pending"
"time":"2022-03-01T12:00:29.053Z","duration":2.90688,"error":0,"options":"merge_request.create"
"time":"2022-03-01T12:00:00.635Z","duration":0.46049,"error":0
"time":"2022-03-01T12:00:39.351Z","duration":0.76487,"error":0,"state":"failed"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436284.html
