LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash script to check if string1 contains string2 (http://www.linuxquestions.org/questions/linux-newbie-8/bash-script-to-check-if-string1-contains-string2-775343/)

Sebbern 12-13-2009 09:37 AM

Bash script to check if string1 contains string2
 
Help! :confused:

I'm going to make a bash script that checks if string1 contains string2.

So far i've got:

Code:

#!/bin/bash

input=$(echo $@)
if [ input == .txt ]
then
echo "yes"
else
echo "no"
fi

But that dosen't work!

Please help :scratch:

colucix 12-13-2009 09:47 AM

Some notes about your script:

1) you don't really need the assignment
Code:

input=$(echo $@)
since you can use $@ directly in the expression inside the if/then construct.

2) you forgot to put a $ sign before the variable name inside the expression:
Code:

if [ $input == .txt ]
without that you just evaluate the equivalence between two strings, which is obviously always false.

3) if using bash version 3 you can try the operator for Regular Expression Match so that your script will look like
Code:

#!/bin/bash
if [[ $@ =~ [.]txt ]]
then
  echo yes
else
  echo no
fi


ghostdog74 12-13-2009 07:21 PM

you can use case/esac

Code:

string1="abcdef"
string2="abc"
case "$string1" in
    *$string2* )
        echo "found"
        ;;
    *) echo "not found"
esac


bsat 12-14-2009 12:05 AM

awk implementation of the same.
BEGIN {
string1="abcdef"
string2="abcd"
if(match(string1,string2))
{
print "found"
}
else
{
print "not found"
}
}

ghostdog74 12-14-2009 12:38 AM

you should put your code in code tags.
Or this as well:
Code:

BEGIN {
  string1="abcdef"
  string2="abcd"
  if( string1 ~ string2){
      print "found"
  }else{
      print "not found"
  }
}


bsat 12-15-2009 04:19 AM

oh, ok I will do that in future . thanks for the info ghostdog :-)


All times are GMT -5. The time now is 02:27 AM.