简体   繁体   English

使用 sed 命令提取子字符串

[英]Extract substring with sed command

I have one file which includes this string in it:我有一个包含此字符串的文件:

2020-12-21 10:46:49.165 INFO: [41] browser.leaveCallAndQuitBrowser() [2020-12-21T10:46:36+0000] [FINE] DevTools WebSocket Event: Runtime.consoleAPICalled 74D7A734C0BD6EEFA60271821A6A2F55 {
   "args": [ {
      "type": "string",
      "value": "2020-12-21T10:46:36.633Z"
   }, {
      "type": "string",
      "value": "[modules/xmpp/xmpp.js]"
   }, {
      "type": "string",
      "value": "\u003CA.connectionHandler>: "
   }, {
      "type": "string",
      "value": "My Jabber ID: recorder@recorder.mydomain/hjE0dMPL"
   } ],
...

I am trying to extract this string from the file recorder@recorder.mydomain.com/vT1gTnAz with sed command but I couldn't get it done.我正在尝试使用sed命令从文件recorder@recorder.mydomain.com/vT1gTnAz提取此字符串,但无法完成。 Can anyone with sed and regex experience help or guide me to do it?任何有sedregex经验的人都可以帮助或指导我这样做吗?

Currently, I am doing it with two commands: I am first getting "My Jabber ID: recorder@recorder.mydomain.com/hjE0dMPL" and then replacing My Jabber ID: with an empty string.目前,我使用两个命令执行此操作:我首先获取“我的 Jabber ID:recorder@recorder.mydomain.com/hjE0dMPL”,然后用空字符串替换我的 Jabber ID:。

grep -EiEio '\bMy Jabber ID: (recorder@[A-Z0-9.-]+\.[A-Z]{2,4}.*)\b' browser.0.txt | sed 's/^My Jabber ID: //g'

It would be more elegant to do it in one command though.不过,在一个命令中完成它会更优雅。

You should use a proper json parser like jq for this but if you cannot use jq for some reason, you can use sed:为此,您应该使用像 jq 这样合适的 json 解析器,但是如果由于某种原因不能使用 jq,则可以使用 sed:

sed -rn 's/(^.*My Jabber ID: )(.*)(".*$)/\2/p' file

Enable regular expressions with -r and then split the line into three sections using regular expressions, substituting the line for just the second section and printing.使用 -r 启用正则表达式,然后使用正则表达式将该行分成三个部分,仅用该行替换第二部分并打印。

You can solve this directly with grep.您可以直接使用 grep 解决此问题。 Suppose your content is in test.txt file:假设您的内容在 test.txt 文件中:

 cat test.txt |grep -Po '"value": "My Jabber ID: \K[^"]*'

will return将返回

recorder@recorder.room-test5.11sight.com/hjE0dMPL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM