0

I have a use case where a variable needs to be checked with multiple sub-strings in OR-condition and produce an output; as below:

if [ ! -z "$var" ]; then
   if [[ $var =~ .*Focus.* ]] || [[ $var =~ .*Wallet.* ]]; then
      ser=`echo $var|cut -d ' ' -f 2`
      echo " $ser is correct"
   else
      ser=`echo $var|cut -d ' ' -f 2`
      echo "!!!! $ser is incorrect !!!!"
    fi
fi

var contains pid and ServiceName. ServiceName is being checked if it contains any of the both substrings. It is running perfectly fine. But I want var to be checked in a list of substrings mentioned in a file instead, so that file can be modified later for more substrings.

kvantour
  • 25,269
  • 4
  • 47
  • 72
anmonu
  • 169
  • 1
  • 13
  • 1
    *I want var to be checked in a list of substring mentioned in a file instead* -- Use awk or grep for this. – dawg Oct 11 '18 at 15:10

2 Answers2

3

Parameter matching can use extended patterns:

#! /bin/bash

check=$(tr '\n' '|' < list_of_terms.txt)
check="@(${check%|})"

for service in Service1 GetFocus WalletLost ; do
    if [[ $service == *$check* ]] ; then
        echo $service matches
    fi
done
choroba
  • 231,213
  • 25
  • 204
  • 289
0

I hope this code will help you.

#!/bin/bash
file="/path/to/substring/file"
if [ ! -z "$var" ]; then
    while IFS= read -r line
    do
        if [[ $var == *"$line"* ]]; then
            echo "match: $line"
            break
        fi
    done <"$file"
fi
menya
  • 1,459
  • 7
  • 8
  • Hi and Welcome To Stack Overlow. Could you please add a bit more information why this answer would work and why you solved it this way? – kvantour Oct 11 '18 at 15:57
  • Hi @menya, if I use this, my else block would print multiple times for the same $ser. – anmonu Oct 11 '18 at 16:11