Skip to content
Advertisement

compare two comma separated strings and list the common values

How many I compare the two comma separated list (master and input) and list the common values among them (result) while preserving the order of elements in master list. For example:

case1:

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

result="city,country"

case 2:

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

result="common,country"

case 3:

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

result="nothing found"

This is what I tried:

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

Advertisement

Answer

Here is one awk-oneliner solution:

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)

Test with your 3 cases:

Case 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

Case 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

Case 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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement