简体   繁体   中英

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. Can anyone with sed and regex experience help or guide me to do it?

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.

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:

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.

You can solve this directly with grep. Suppose your content is in test.txt file:

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

will return

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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