0

I have a string, such as time=1234, and I want to extract just the number after the = sign. However, this number could be in the range of 0 and 100000 (eg. - time=1, time=23, time=99999, etc.).

I've tried things like $(string:5:8}, but this will only work for examples of a certain length.

How do I get the substring of everything after the = sign? I would prefer to do it without outside commands like cut or awk, because I will be running this script on devices that may or may not have that functionality. I know there are examples out there using outside functions, but I am trying to find a solution without the use of such.

2 Answers 2

6
s=time=1234
time_int=${s##*=}
echo "The content after the = in $s is $time_int"

This is a parameter expansion matching everything matching *= from the front of the variable -- thus, everything up to and including the last =.

If intending this to be non-greedy (that is, to remove only content up to the first = rather than the last =), use ${s#*=} -- a single # rather than two.


References:

Sign up to request clarification or add additional context in comments.

Comments

3

if time= part is constant you can remove prefix by using ${str#time=}

Let's say you have str='time=123123' if you execute echo ${str#time=} you would get 123123

3 Comments

Since the OP is following best practices by using lower-case variable names, you might do the same.
...re: "best practices", see pubs.opengroup.org/onlinepubs/009695399/basedefs/…, defining conventions for naming of environment variables; since shell variables share a namespace (which is to say, for instance, that setting a shell variable named PATH will override the contents of the environment variable PATH), those conventions apply to shell variables as well.
Thanks updated as per your advice but the reason I used uppercase was so it wouldn't be confused with time= part :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.