I have a file as below
"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
I want to add " at the end but only to lines ending as a string
I gave sed -i 's/$/",/' filename
but it adds quotes to end of all the lines.
Desired output is
"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"
Is there a way to achieve this?
CodePudding user response:
You can use
sed 's/:"[^"]*$/&"/' file > tmp && mv tmp file
sed -i 's/:"[^"]*$/&"/' file # GNU sed
The 's/:"[^"]*$/&"/'
command means:
:"[^"]*$
- matches a:"
substring and then zero or more chars other than"
till end of string&"
- replaces the match with itself and a"
char.
See the 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"
Output:
"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"
CodePudding user response:
Suggesting an awk
solution:
awk '/[[:alpha:]]$/{$0=$0"\""}1' input.txt
CodePudding user response:
Using 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"