如何比较两个逗号分隔的字符串(主字符串和输入字符串),使得如果输入字符串的任何值与主字符串的值匹配,则echo" present"否则回声"缺席"。 例如:
master_list="customer,products,address"
input="relations,country,customer"
给出echo#34; present" (因为客户同时存在)
master_list="customer,products,address"
input="address,customer,car"
给出echo#34; present" (因为客户和地址都存在于两者中)
master_list="customer,products,address"
input="address"
给出echo#34; 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
但它不起作用。
答案 0 :(得分:2)
您可以通过调用grep
和tr
来为此比较创建一个函数:
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
答案 1 :(得分:1)
另一种方法是通过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变量作为主变量传递。将输入和模式匹配中的每个逗号分隔值与主数据相匹配。如果匹配集nomatch标记为0,则将其设置为1.最后检查nomatch标记并打印出现在或不存在。