0

I run the command grep to get certain output and store it into a variable. The output of grep command is:

5.3.1-6.2011171513.ASMOS6

but I need to only parse out 5.3.1-6 and store that version in a variable. How can I do that?

2 Answers 2

1

What about this?

TEXT=5.3.1-6.2011171513.ASMOS6
RES=$(echo $TEXT | cut -d. -f-3)

We cut the string on . and then get the first 3 pieces.

With awk

RES=$(echo $TEXT | awk -F. 'OFS=FS {print $1,$2,$3}')

OFS=FS meaning we get the delimiter to print that was defined with -F.

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

5 Comments

Awesome !! Both of them work great. Thank You! I was using regex (\\d)(\\.)(\\d)(\\.)(\\d)(-)(\\d)
Good to read it worked for you, @JumpOffBox! Sometimes either cut or awk are easier to handle and understand. If you are done, you can mark the question as answered. Cheers!
Could you also suggest why I was going wrong with above reg ex?
Please indicate the exact command you were using. Were you using sed with regex (\\d)...?
Thanks ! Actually, I was looking to use same awk and cut to parse version e.g in string res3=asmos-no-5.3.1-6.2011171513.ASMOS6, but delimiter either gives me 5.3.1 or 1-6 but not complete "5.3.1-6", hence I used reg ex $(echo $res3| sed -e 's/.*[0-9]\.[0.9]\.[0-9]\-[0-9].*/g') which was not working even cut or awk was not working to get 5.3.1-6 in above res3 string> Thanks !
1

As you tag says linux, I'll assume that you have a modern grep that supports the -o option.

You can do

var=$(grep -o 'regex' file)

To capture just the regex to a variable.

Unfortunately, I don't understand the problem you're having getting just 5.3.1-6, you have to edit your question to show us the regex youare currently using.

IHTH

2 Comments

The above said sting is the output I get and store it in a variable. $var = 5.3.1-6.2011171513.ASMOS6 I need stored in another variable $var2, only 5.3.1-6 from string($var) and do not need rest of the characters in the string. The issue is the version can change this time it is 5.3.1-6, next time it could be 7.4.5-2
The above said sting is the output I get and store it in a variable. $var = 5.3.1-6.2011171513.ASMOS6 I need stored in another variable $var2, only 5.3.1-6 from string($var) and do not need rest of the characters in the string. The issue is the version can change this time it is 5.3.1-6, next time it could be 7.4.5-2 I use reg ex (\\d)(\\.)(\\d)(\\.)(\\d)(-)(\\d)

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.