2017-08-30 57 views
1

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

案例1:

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

result="city,country" 

的情况下2:

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

result="common,country" 

的情况下3:

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)" 

回答

2

这里是一个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) 

测试你的三种情况:

案例1

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 

案例2

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 

案例3

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 
+0

谢谢。当输入来自用户时,当master已经被定义为变量时,我试图改变你的脚本。然而,看起来我犯了一些错误: result =“$(awk -F,-va = $ master'{for(i = 1; i <= NF; i ++){if(a〜$ i ){print $ i}}}'<<< $ input)“ – Jaanna

+0

你没有改变我的密码,你正在重写我的密码。您正在使用不同的方法来解决问题。不知道你为什么把评论放在我的答案下。如果'master'是由用户提供的,则没有区别。我使用'master'作为**已经定义的** shell变量,'$ input' @Jaanna也是如此 – Kent

2

您可以使用grepBASH字符串操作:

cmn() { 
    local master="$1" 
    local input="$2" 
    result=$(grep -Ff <(printf "%s\n" ${input//,/ }) <(printf "%s\n" ${master//,/ })) 
    echo "${result//$'\n'/,}" 
} 


cmn "common,city,country" "city,country" 
city,country 

cmn "common,city,country" "country,pig,cat,common" 
common,country 

cmn "common,city,country" "pigs,cars,train" 
+1

我最喜欢它。你可以使用'result = $(grep -Ff <(printf“%s \ n”$ {input //,/})<(printf“%s \ n”$ {master //,/}))'' 'echo -n'? –

+0

非常感谢@WalterA的建议。它现在被编辑回答。 – anubhava

1

可以使用通讯工具

my_comm() { 
    res=$(comm -12 <(echo "$1" | tr ',' '\n' | sort) <(echo "$2" | tr ',' '\n' | sort) | xargs | tr ' ' ',') 
    [[ -z $res ]] && echo nothing found || echo $res 
} 

> my_comm common,city,country city,country 
city,country 
> my_comm common,city,country country,pig,cat,common 
common,country 
> my_comm common,city,country pigs,cars,train 
nothing found 
相关问题