Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string match question 1

Status
Not open for further replies.
Mar 31, 2004
151
US
I want to see if a string has a word. Ex: $x has "DATA"
Could that be done using match? i.e If the string has word, echo yes otherwise echo no
 
Try somehting like :

Code:
if [ $var == "hello" ]
then
  echo "got it"
else 
  echo "nope"
fi
 
Thanks but I am looking for a pattern in a string. Something like a substring. Not the entire string.
 
How about:
Code:
#!/usr/local/bin/bash
x="dijowqjodjqojdojojiqoidjowjiDATAqwdqpojdqoijdjiqwj2"
y="dijowqjojdojojiqoidjowjidqoijdjiqwj2"
for var in $x $y
do
    z=${var/DATA/}
    if [ $z != $var ] ; then
        echo "$var contains DATA"
    else
        echo "$var does not contain DATA"
    fi
done
Cheers, Neil
 
toolkit, Thanks. But it's giving the following:

test.sh[6]: z=${var/DATA/}: The specified substitution is not valid for this command.
 
This might be for bash only. What shell are you using?
As stefanwagner suggested, this may be more portable:
Code:
#!/bin/sh
a="oqqiquiudqhdiDATAdqjwodqji"
b="jqihdqudyqugdyqgdugyqugyug"
for var in $a $b
do
    case $var in
        *DATA*)
            echo "$var yes";;
        *)
            echo "$var no";;
    esac
done
Cheers, Neil
 
Code:
#!/bin/ksh
a="oqqiquiudqhdiDATAdqjwodqji"
b="jqihdqudyqugdyqgdugyqugyug"

for var in $a $b
do
  if [[ ${var} == @(*DATA*) ]]; then
     echo "$var yes";
  else    
     echo "$var no";
  fi;
done;

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Vlad,

I believe == should just be =.

Code:
#!/bin/ksh
a="oqqiquiudqhdiDATAdqjwodqji"
b="jqihdqudyqugdyqgdugyqugyug"

for var in $a $b
do
  if [[ ${var} = @(*DATA*) ]]; then
     echo "$var yes";
  else    
     echo "$var no";
  fi;
done;

John
 
sorry - my bad!

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top