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,239
  • 3
  • 13
  • 20

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
  • 69,796
  • 4
  • 95
  • 132
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
  • 761,203
  • 64
  • 569
  • 643
2

With sed:

your-command | sed 's/.*"token":"\([^"]*\)".*/\1/'
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1
YourStreamOrFile | sed -n 's/.*"token":"\([a-f0-9]\{32\}\)".*/\1/p'

doesn not return a full string if not corresponding

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43