Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Shell Script - String Comparison with wildcards

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?

like image 423
AlexT82 Avatar asked Nov 10 '13 15:11

AlexT82


People also ask

How do you compare strings in a shell script?

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.

What does ${} mean in shell script?

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.

How do you use wildcards in Linux?

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.


1 Answers

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.

like image 180
glenn jackman Avatar answered Sep 20 '22 11:09

glenn jackman