I am trying to see if a string is part of another string in shell script (#!bin/sh).
The code i have now is:
#!/bin/sh #Test scriptje to test string comparison! testFoo () { t1=$1 t2=$2 echo "t1: $t1 t2: $t2" if [ $t1 == "*$t2*" ]; then echo "$t1 and $t2 are equal" fi } testFoo "bla1" "bla"
The result I'm looking for, is that I want to know when "bla" exists in "bla1".
Thanks and kind regards,
UPDATE: I've tried both the "contains" function as described here: How do you tell if a string contains another string in Unix shell scripting?
As well as the syntax in String contains in bash
However, they seem to be non compatible with normal shell script (bin/sh)...
Help?
When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.
Here are all the ways in which variables are substituted in Shell: ${variable} This command substitutes the value of the variable. ${variable:-word} If a variable is null or if it is not set, word is substituted for variable.
Option with '*. ' The wildcard '*' means it will match any number of characters or a set of characters. For example, S**n will match anything between S and n.
When using ==
or !=
in bash you can write:
if [[ $t1 == *"$t2"* ]]; then echo "$t1 and $t2 are equal" fi
Note that the asterisks go on the outside of the quotes and that the wildcard pattern must be on the right.
For /bin/sh, the =
operator is for equality only, not pattern matching. You can use case
for pattern matching though:
case "$t1" in *"$t2"*) echo t1 contains t2 ;; *) echo t1 does not contain t2 ;; esac
If you're specifically targeting Linux, I would assume the presence of /bin/bash.
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