如何将 " 添加到 linux 中特定行的末尾

how to add " to end of specific lines in linux

我有一个文件如下

"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"

有办法实现吗?

您可以使用

sed 's/:"[^"]*$/&"/' file > tmp && mv tmp file
sed -i 's/:"[^"]*$/&"/' file # GNU sed

's/:"[^"]*$/&"/'命令的意思是:

  • :"[^"]*$ - 匹配 :" 子字符串,然后匹配 " 以外的零个或多个字符,直到字符串结尾
  • &" - 用自身和一个 " 字符替换匹配。

参见 online demo:

#!/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"

建议 awk 解决方案:

awk '/[[:alpha:]]$/{[=10=]=[=10=]"\""}1' input.txt

使用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"