1

File 1:

happy
sad
calm
palm

File 2:

palm
dream
calm

I want to compare the two files and display only those line that are common in both the files, but I want to maintain the order of File 2. My output should be:

palm
calm

I know I can use comm after sorting the files but I want to maintain the order. Is there any way to do this?

5

Use grep:

$ grep -Ff f1 f2
palm
calm

man grep:

   -F, --fixed-strings
          Interpret PATTERN as a list of fixed strings (instead of regular
          expressions), separated by newlines,  any  of  which  is  to  be
          matched.
   -f FILE, --file=FILE
          Obtain patterns from FILE, one per line.  If this option is used
          multiple times or is combined with  the  -e  (--regexp)  option,
          search  for  all  patterns  given.  The empty file contains zero
          patterns, and therefore matches nothing.
  • Also, this should probably use -x. – Kusalananda Oct 16 '18 at 9:55

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.