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:
JavaScript
x
master="common,city,country"
input="city,country"
result="city,country"
case 2:
JavaScript
master="common,city,country"
input="country,pig,cat,common"
result="common,country"
case 3:
JavaScript
master="common,city,country"
input="pigs,cars,train"
result="nothing found"
This is what I tried:
JavaScript
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:
JavaScript
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
JavaScript
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
JavaScript
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
JavaScript
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