0

When given a string I want to search for a substring which matches two characters (9&0. 0 should be the last character in that substring) and exactly two characters in between them

string="asd20 92x0x 72x0 YX92s0 0xx0 92x0x"
#I want to select substring YX92s0 from that above string

for var in $string
do
if [[ "$var" == *9**0 ]]; then
    echo $var  // Should print YX92s0 only
fi
done

Obviously this above command doesn't work.

2 Answers 2

1

You match each element against the pattern *9??0. There are several ways you can do this; here's one that uses the string to set the positional parameters in a subshell, then iterates over them in a for loop:

( set -- $string
  for elt; do [[ $elt == *9??0 ]] && { echo "found"; exit; }; done )
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry I missed to add for loop in my original question. There was one actually. My question was about the search pattern. When I changed my pattern *9**0 to *9??0 that if condition worked just fine :). Thanks
0
string="asd20 92x0x 72x0 X92s0 0xx0"

if [[ $string =~ [[:space:]].?9.{2}0[[:space:]] ]]; then
    echo "found"
fi

Or better, taking advantage of word spliting :

string="asd20 92x0x 72x0 X92s0 0xx0"

for s in $string; do
    if [[ $s =~ (.*9.{2}0) ]]; then
        echo "${BASH_REMATCH[1]} found"
    fi
done

This is regex with .

5 Comments

This solution didn't work on string "X9xx0 9xx0x". It returned 9xx0x instead of X9xx0
copy/paste one more time, post edited accordingly. I've made the assumtion that there's only one character or nothing between the leading space and the 9 digit
IMO the second solution would need a $-anchor.
I was using a for loop like your second solution.. that regex didn't work on "x9xx0 9xx0x". It selected 9xx0x instead of wanted x9xx0
for s in $string; do if [[ $s == *9??0 ]]; then echo $s; fi done WORKED FINE :)

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.