[英]string find and replace with sed
This contains the following information in a file. 它在文件中包含以下信息。
17:06:31.301 [blabal] DEBUG blablabla1
17:06:31.302 [blabal] DEBUG blablabla2
17:06:31.303 [blabal] DEBUG blablabla3
Fetching the contents of that file cat to wonder whether I would like to change it to json format. 获取该文件cat的内容,以询问是否要将其更改为json格式。
[{"time" : "17:06:31.301", "log" : "[blabal] DEBUG blablabla1"}
{"time" : "17:06:31.302", "log" : "[blabal] DEBUG blablabla2"}
{"time" : "17:06:31.303", "log" : "[blabal] DEBUG blablabla3"}]
Is it possible in this way? 这样可以吗?
$ sed -r 's/^([^ ]+) (.*)/{"time" : "\1", "log" : "\2"}/; 1s/^/[/; $s/$/]/' file
[{"time" : "17:06:31.301", "log" : "[blabal] DEBUG blablabla1"}
{"time" : "17:06:31.302", "log" : "[blabal] DEBUG blablabla2"}
{"time" : "17:06:31.303", "log" : "[blabal] DEBUG blablabla3"}]
sed -r
Start sed
with extended regular expressions. 启动
sed
扩展正则表达式。 For BSD sed, use -E
in place of -r
. 对于BSD sed,使用
-E
代替-r
。
s/^([^ ]+) (.*)/{"time" : "\\1", "log" : "\\2"}/
Divide the line up into the first word, denoted \\1
, and all the rest, denoted \\2
and then put it into json form. 将行划分为第一个单词,表示为
\\1
,其余所有单词表示为\\2
,然后将其放入json形式。
1 s/^/[/
On the first line, prepend everything with an opening square bracket [
. 在第一行,将所有内容放在方括号
[
。
$ s/$/]/
On the final line (denoted $
), locate the end of the line, also denoted by $
, and put a closing square bracket ]
there. 在最后一行(表示为
$
)上,找到该行的末尾(也用$
表示),然后在其中放置一个右方括号[ ]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.