1

I have run into a problem while doing some coding, and I need to compare two files, here is an example input file inputfile1.txt:

car
php
module
so
js
node
array

and another input file: inputfile2.txt:

car
module
js
array
so

The two files are compared, and as you see on inputfile2.txt, node and php does not exist.

Here is the output file outputfile1.txt produced by command inputfile1.txt inputfile2.txt > outputfile1.txt:

car
module
js
array
so
php
node

The output file adds missing values that appeared on inputfile1.txt, but not inputfile2.txt. They are the last two lines.

I have tried a few things with diff and grep but none shows my desired output.

I am using OSX.

  • 2
    There are some questions similar to this answered before. You should search the site first. Example here: unix.stackexchange.com/questions/121222/… – cuonglm Nov 13 '14 at 3:25
  • 1
    cat inputfile{1,2}.txt | sort | uniq > newfile will do it if you don't care about sorting. – terdon Nov 13 '14 at 3:54
  • @cuonglm Yes, i always try searching, but the titles are almost never similar. – DisplayName Nov 13 '14 at 5:14
  • 2
    there is also a comm command which show lines in file 1 only, file 2 only or both file. – Archemar Nov 13 '14 at 6:53
  • 1
    This question is missing a question. I guess you're looking for a way to implement command? Do you care about the order of elements in the output? – Gilles 'SO- stop being evil' Nov 13 '14 at 23:03
1

with grep:

grep -Fxvf file2 file1 >> file2 # append to end of file2

With sort:

sort -u file[12] > output
  • +1 But you may want grep -vxFf file2 just in case file2 contains any regexp meta-characters, such as ., etc., and to ensure that all matches are entire-line matches. Also, your second grep command has a stray ). – Jim L. Jul 20 '19 at 23:04
  • @JimL. edited, I think this was answered by me when I was new to the site : ) – αғsнιη Jul 21 '19 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.