0

we have to write a shell program that will tell the position (index) of the substring in a given string.

  • sample input:-
 Code Quotient - Get Better at Programming 
 at 
  • sample output :- 28

i have written the code but it is giving -1 in every case..can pls someone help me finding the error.

#!/bin/bash
read a
read b
if [[ "$a" == "$b" ]]; then
    rest=${a#*$b}
    echo $(( ${#a} - ${#rest} - ${#b} +1 ))
else
    echo "-1"
fi
2
  • Change == to =~
    – nezabudka
    Aug 11 '21 at 5:14
  • 1
    Perhaps it will be easier this way: rest=${a%%$b*} echo $((${#rest} + 1))
    – nezabudka
    Aug 11 '21 at 6:14
1

Your expression [[ "$a" == "$b" ]] checks to see if the two strings are the same. Since one is intended to be a substring of the other they will almost never match, so the if cannot succeed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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