2

Everyone!! I want to get specific substring from stdout of command.
stdout:

{"response": {"id":"110200dev1","success":"true","token":"09ad7cc7da1db13334281b84f2a8fa54"},"success":"true"}

I need to get a hex string after token without quotation marks, the length of hex string is 32 letters.I suppose it can be done by sed or egrep. I don't want to use awk here. Because the stdout is being changed very often.

Bilow Yuriy
  • 1,149
  • 3
  • 12
  • 19

4 Answers4

4

grep's nature is extracting things:

grep -Po '"token":"\K[^"]+'
  • -P option interprets the pattern as a Perl regular expression.
  • -o option shows only the matching part that matches the pattern.
  • \K throws away everything that it has matched up to that point.

Or an option using sed...

sed 's/.*"token":"\([^"]*\)".*/\1/'
hwnd
  • 67,942
  • 4
  • 86
  • 123
4

This is an alternate gnu-awk solution when grep -P isn't available:

awk -F: '{gsub(/"/, "")} NF==2&&$1=="token"{print $2}' RS='[{},]' <<< "$string"
09ad7cc7da1db13334281b84f2a8fa54
anubhava
  • 713,503
  • 59
  • 514
  • 593
2

With sed:

your-command | sed 's/.*"token":"\([^"]*\)".*/\1/'
Cyrus
  • 77,979
  • 13
  • 71
  • 125
1
YourStreamOrFile | sed -n 's/.*"token":"\([a-f0-9]\{32\}\)".*/\1/p'

doesn not return a full string if not corresponding

NeronLeVelu
  • 9,588
  • 1
  • 22
  • 41