Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I have a variable with some text in it. I need to get a specific bit of information out of it. For example I have

export OUTPUT="Running \"protractor:admin\" (protractor) task Using ChromeDriver directly... [launcher] Running 1 instances of WebDriver Jasmine version: 1.3.1 revision 1354556913 SauceOnDemandSessionID=5c72e54365e9bb559ea389dc164ba754 job-name=Admin"

I need 5c72e54365e9bb559ea389dc164ba754 in an variable SAUCE_ID. The actual SessionID changes each run of the script so I need someway to pull it out. It is always preceded by SauceOnDemandSessionID= and followed by job-name=.

share|improve this question

3 Answers 3

up vote 3 down vote accepted

Use the shell's string manipulation features that come with parameter expansion. These features are present in all non-antique Bourne-style shells including dash, bash and ksh.

suffix=${OUTPUT#*SauceOnDemandSessionID=}
SAUCE_ID=${suffix%%[!0-9A-Fa-f]*}
share|improve this answer

If the ID is always the same length, and composed of only the letters a through f and numbers, and there are no similar strings in the output, you could do this:

SAUCE_ID="$(echo $OUTPUT | egrep -o '[0-9a-f]{32}')"

It searches for a string of 32 characters that are either a number in 0-9 or a letter in a-f.

To allow variation in the length of the string, use something like this:

SAUCE_ID="$(echo $OUTPUT | egrep -o '[0-9a-f]{26,38}')"

This example matches any of those strings with between 26 and 38 characters. You could also use this to match strings with at least 26 characters:

SAUCE_ID="$(echo $OUTPUT | egrep -o '[0-9a-f]{26,}')"
share|improve this answer
    
Unfortunately, I'm not 100% the length will always be 32. –  Justin808 Apr 23 at 0:09
    
It's possible to allow multiple lengths. I edited my answer with an example. –  Ringstaart Apr 23 at 0:12

Using grep with PCRE, you can use the regex:

SauceOnDemandSessionID=\K[^ ]*(?= job-name)

Test:

$ SAUCE_ID=$(grep -Po "SauceOnDemandSessionID=\K[^ ]*(?= job-name)" <<< "$OUTPUT")
$ echo "$SAUCE_ID"
5c72e54365e9bb559ea389dc164ba754

It will be work in all cases given you have SauceOnDemandSessionID= before and job-name after the pattern.

share|improve this answer
    
I get: usage: grep [-abcDEFGHhIiJLlmnOoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]] [-e pattern] [-f file] [--binary-files=value] [--color=when] [--context[=num]] [--directories=action] [--label] [--line-buffered] [--null] [pattern] [file ...] –  Justin808 Apr 23 at 0:09
    
@Justin808: How did you run it? –  heemayl Apr 23 at 0:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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