在Shell脚本变量中搜索相同的字符串

时间:2018-05-01 07:45:18

标签: bash shell variables unix grep

我有一个shell变量,whitch包含一个列表     $a = Albania Andorra Armenia Austria Azerbaijan Belarus Belgium. 我通过html页面获得一个变量。它是$b。 目标是,如果$b不完全相同,例如' A'或者' Andor',脚本写:fail,但$b = Andorra,脚本写:success

2 个答案:

答案 0 :(得分:0)

您可以使用以下脚本:

<强> SCRIPT:

$ cat test_countries.sh 
#!/bin/bash

a="Albania Andorra Armenia Austria Azerbaijan Belarus Belgium"
b=$1 #read the first argument passed to the script

if [ `echo $a | grep -wc $b` -ge 1 ] #run a grep command that will count the number of word matches then branch depending on the result  
then 
        echo success
        exit 0 #default return code when success
else
        (echo fail >&2) #fail is output on stderr
        exit 1 #another value different than 0 in case of error 
fi

<强>样本:

$ ./test_countries.sh Belgium
success

$ ./test_countries.sh B
fail

答案 1 :(得分:0)

仅使用GNU awk \< ... \>

$ awk -v a="$a" -v b="$b" '
BEGIN {
    if(a~"\\<"b"\\>")
        print "success"
    else 
        print "fail"
}'

其他问题可能适用于此:

$ awk -v a="$a" -v b="$b" '
BEGIN {
    split(a,c)
    for(i in c)
        if(b==c[i]) {
            print "success"
            exit
        } 
    print "fail"
}'