noober
noober

Reputation: 1505

unix command to perform list comparisons equivalent to a set operation

What unix command/utility can I use to create my final list of names based on my 2 lists below? This would be like doing a SET operation. However, the main comparison has to be against NameList1. If NameList2 has an extra name(s), don't include it in the master list.

Note: I cannot have it sorted (alphabetical, etc). I need to preserve the column position (natural order) as I've already provided in my list top, down. Thanks for your help.

NameList1:

Joe
John
Mary
Mike
Allan
David
Andrew
Matt

NameList2:

Joe
John
Mary
George
Jeff
Allan
David
Andrew
Frank

If I do a diff with a side-by-side compare you can see the comparison. Like so:

-bash-4.1$ diff --side-by-side NameList1.txt NameList2.txt
Joe                             Joe
John                                John
Mary                                Mary
Mike                                  | George
                                  > Jeff
Allan                               Allan
David                               David
Andrew                              Andrew
Matt                                  | Frank

The outcome, expected for my final list would be:

Joe
John
Mary
Mike
Allan
David
Andrew
Matt

Where George, Jeff, Frank is removed from NameList1. How can I product this final list? Is there a better tool command? Am I using diff correctly?

Upvotes: 0

Views: 53

Answers (1)

ring bearer
ring bearer

Reputation: 20783

This can be achieved using a simple join command. In my Mac, following gives expected result

join -a1 NameList1 NameList2

>      -a file_number
>                  In addition to the default output, produce a line for each
>                  unpairable line in file file_number.

Edit

On Linux, --no-checkorder option would avoid checking sorted order on inputs.

join -a1 --nocheck-order NameList1 NameList2

Upvotes: 1

Related Questions