比较两个逗号分隔的字符串并列出常用值

时间:2017-08-30 08:06:10

标签: linux bash

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

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

3 个答案:

答案 0 :(得分:2)

您可以grep使用BASH字符串操作:

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 :(得分: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)

用你的3个案例进行测试:

案例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

答案 2 :(得分: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