If I have the text in a shell variable, say $a
:
a="The cat sat on the mat"
How can I search for "cat" and return 4 using a Linux shell script, or -1 if not found?
Using Grep The grep command can also be used to find strings in another string. In the following example, we are passing the string $STR as an input to grep and checking if the string $SUB is found within the input string. The command will return true or false as appropriate.
To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
With bash
a="The cat sat on the mat" b=cat strindex() { x="${1%%$2*}" [[ "$x" = "$1" ]] && echo -1 || echo "${#x}" } strindex "$a" "$b" # prints 4 strindex "$a" foo # prints -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With