繁体   English   中英

比较两个逗号分隔的字符串

[英]compare two comma separated strings

我如何比较两个逗号分隔的字符串(主字符串和输入字符串),使得如果输入字符串的任何值与主字符串的值匹配,则回显“ present”,否则回显“ absent”。 例如:

master_list="customer,products,address"
input="relations,country,customer"

给出回显“ present”(因为两个客户均在场)

master_list="customer,products,address"
input="address,customer,car"

给出回显“ present”(因为同时存在客户和地址)

master_list="customer,products,address"
input="address"

给出回显“ present”(因为两个地址都存在)

master_list="customer,products,address"
input="car"

给回声“不存在”(因为没有匹配项)

master_list="customer,products,address"
input="humans,car"

给回声“不存在”(因为没有匹配项)

我尝试了以下方法:

if [[ ",$master_list," =~ ",$input," ]]; then
  echo "present"
else
  echo "absent"
fi

但它不起作用。

您可以通过在内部调用greptr来进行此比较的功能:

compare() {
   grep -qFxf <(tr ',' '\n' <<< "$2") <(tr ',' '\n' <<< "$1") &&
   echo "present" || echo "absent"
}

然后将其称为:

compare "customer,products,address" "relations,country,customer"
present

compare "customer,products,address" "car"
absent

compare "customer,products,address" "address,customer,car"
present

另一种方法是通过awk:

awk -F, -v master=$master_list '{ for (i=1;i<=NF;i++) { if (master ~ $i) { nomatch=0 } else { nomatch=1 } } } END { if ( nomatch==1 ) { print "absent" } else { print "present" } }' <<< $input

将字段定界符设置为,然后将master_list变量作为master传递。 将输入中的每个逗号分隔值和与主机的模式匹配。 如果有一个匹配集,nomatch标记为0,否则将其设置为1。最后检查nomatch标记,并相应地打印存在或不存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM