gpt4 book ai didi

linux - 比较两个逗号分隔的字符串并列出共同的值

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:29 25 4
gpt4 key购买 nike

我比较了两个逗号分隔列表(主列表和输入列表)并列出了它们之间的共同值(结果),同时保留了主列表中元素的顺序。例如:

案例一:

master="common,city,country"
input="city,country"

result="city,country"

案例二:

master="common,city,country"
input="country,pig,cat,common"

result="common,country"

案例三:

master="common,city,country"
input="pigs,cars,train"

result="nothing found"

这是我尝试过的:

result="$(awk -F, -v master_list=$master'{ for (i=1;i<=NF;i++) { if (master_list~ $i) { echo $i } } } END ' <<< $input)"

最佳答案

这是一个 awk-oneliner 解决方案:

awk -v RS=",|\n" 'NR==FNR{a[$0]=1;next}
{a[$0]++}a[$0]>1{r=r?r","$0:$0}
END{print r?r:"Nothing found"}' <(<<< $master) <(<<<$input)

测试你的 3 个案例:

案例一

kent$ master="common,city,country"
kent$ input="city,country"
kent$ result=$(awk -v RS=",|\n" 'NR==FNR{a[$0]=1;next}{a[$0]++}a[$0]>1{r=r?r","$0:$0}END{print r?r:"Nothing found"}' <(<<< $master) <(<<<$input))
kent$ echo $result
city,country

案例二

kent$ master="common,city,country"
kent$ input="country,pigs,cat,common"
kent$ result=$(awk -v RS=",|\n" 'NR==FNR{a[$0]=1;next}{a[$0]++}a[$0]>1{r=r?r","$0:$0}END{print r?r:"Nothing found"}' <(<<< $master) <(<<<$input))
kent$ echo $result
country,common

案例三

kent$ master="common,city,country"
kent$ input="pigs,cars,train"
kent$ result=$(awk -v RS=",|\n" 'NR==FNR{a[$0]=1;next}{a[$0]++}a[$0]>1{r=r?r","$0:$0}END{print r?r:"Nothing found"}' <(<<< $master) <(<<<$input))
kent$ echo $result
Nothing found

关于linux - 比较两个逗号分隔的字符串并列出共同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45955108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com