Shell Script: Check if a string contains a substring








#!/bin/bash

S="Pineapple"

if [[ "${S}" == *apple* ]]; then
    echo "Yes"
else
    echo "No"
fi



7 comments:

  1. S="Pineapple"

    if [[ "`echo ${S}|grep apple `" != "" ]]; then
    echo "Yes"
    else
    echo "No"
    fi

    ReplyDelete
    Replies
    1. S="Pineapple"

      if [[ ! -z $(echo ${S} | grep apple) ]]; then
      echo "Yes"
      else
      echo "No"
      fi

      Delete
  2. Hi,
    And new way.

    S="Pineapple"

    if [ "${S}" =~ "apple" ]; then
    echo "Yes"
    else
    echo "No"
    fi

    It's work fine for linux.

    by pepsi

    ReplyDelete
  3. how do you check if a file contains a string without using sed or awk or grep command?

    ReplyDelete
    Replies
    1. while read line
      do
      if [[ "${line}" == *apple* ]]; then
      echo "YES"
      break
      fi
      done < /path/to/yourfile.txt

      Delete