1

I saw many examples, but for some reason it still does not work for me.

This is the command I'm executing:

NUMBER=$(docker logs vault | grep Token)
NUMBER=${NUMBER##*": "}
NUMBER=$(echo $NUMBER | sed 's/^token=(.*)$//g')
echo $NUMBER

I want to get the value after '=', which is a string basically. I tried using GREP, and other regex's but I either get nothing, or just the original string.

Please advise.

6
  • which os are you using?
    – Nisba
    Commented Feb 20, 2018 at 20:03
  • You're a) using () capture groups with Basic Regular Expressions, where they have to be \(\) (or use ERE instead, sed -E/sed -r) and b) you're removing the complete line, but you want to re-insert the captured group again. Commented Feb 20, 2018 at 20:03
  • 2
    Better to use cut here echo 'token=dsa32e3' | cut -d= -f2
    – anubhava
    Commented Feb 20, 2018 at 20:04
  • 2
    Or, if supported, number=$(echo token=dsa32e3);number=${number#*=}
    – choroba
    Commented Feb 20, 2018 at 20:10
  • 1
    @anubhava, thank you! please post an answer so I'll accept it. Commented Feb 20, 2018 at 20:25

2 Answers 2

1

To get text after a delimiter better to use cut instead of sed as in this example:

echo 'token=dsa32e3' | cut -d= -f2

dsa32e3
  • -d= sets delimiter as = for cut
  • -f1 makes cut print first field
9
  • I encounter another at the moment, I get back the string I wanted but with an additional ANSI character: "48372d06-03a5-f2a0-8428-ecd58cf57424\u001b[0m", what is this '\u001b[0m' string? and how do I get rid of it? Commented Feb 21, 2018 at 11:34
  • Is this \u001b[0m part of your original string as well?
    – anubhava
    Commented Feb 21, 2018 at 14:53
  • Nope, it's seems to be added after I use the grep command. Commented Feb 21, 2018 at 14:59
  • 1
    I've added the additional command I perform. Commented Feb 21, 2018 at 15:25
  • 1
    Solved it using sed -r "s/\x1B[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" The string at the end was ANSI colour code. Commented Feb 22, 2018 at 9:23
1

With sed you can simply remove the token=, with

NUMBER=$(echo token=dsa32e3 | sed 's/^token=//g') 
echo $NUMBER

Other non-regexp based alternatives are possible, as other users pointed out.

Another fun possibility is using the negative lookbehind, not supported by sed, so I used perl.

NUMBER=$(echo token=dsa32e3 | perl -pe 's/.*(?<=token=)([a-z0-9]*)/$1/g')
echo $NUMBER

Not the answer you're looking for? Browse other questions tagged or ask your own question.