0

I am new to bash. I have experience in java and python but no experience in bash so I'm struggling with the simplest of tasks.

What I want to achieve is I want to look through the string and find certain sub strings, numbers to be exact. But not all numbers just number that are followed by " xyz". For example:

string="Blah blah boom boom 14 xyz foo bar 12 foo boom 55 XyZ hue hue 15 xyzlkj 45hh."

And I want to find numbers: 14 55 and 15

How would I go about that?

2 Answers 2

2

You can use grep with lookahead

echo "$string" | grep -i -P -o '[0-9]+(?= xyz)'

Explanation:

  • -i – ignore case
  • -P – interpret pattern as a Perl regular expression
  • -o – print only matching
  • [0-9]+(?= xyz) – match one or more numbers followed by xyz

For more information see:

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

4 Comments

I will take this one because it is explained better and provides some additional references. Thank you good sir.
Hi, i just have a follow up question. I want to add those numbers up and just print out the sum but I'm not sure how to do that. I tried: $result=expr $result + ${"$line" | grep -i -P -o '[0-9]+(?= xyz)'} and I get a ${"$line" | grep -i -P -o '[0-9]+(?= lešnik)'}: bad substitution
Hi, first declare result sum – declare -i sum, then foreach results and add each result to sum – for num in $(echo "$string" | grep -i -P -o '[0-9]+(?= xyz)'); do sum+=$num; done
That did it for me tyvm.
0

grep + cut approach (without PCRE):

echo $string | grep -io '[0-9]* xyz' | cut -d ' ' -f1

The output:

14
55
15

Comments

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.