• Blogging
  • Freebies
  • Freeware
  • How-To
  • Make Money Online
  • Mobile
  • Home >> Unix >> Find / List Lines from one file that are not in other file using bash/ksh Shell in Unix – Unix Commands

    Find / List Lines from one file that are not in other file using bash/ksh Shell in Unix – Unix Commands


    Finding / Listing / Printing Lines that are there in one file but not in other file in unix. Well these situations occur rarely. But, this type of query is required daily in SQL and can be easily done using “NOT IN” clause.

    There are multiple ways to print Lines in one file but not in another file using Shell like Bash and Ksh in UNIX. Below are few ways:

    Check out the Difference Between Unix and Linux

    For instance we have a file file1.txt containing following lines:

    Nihar
    Rahin
    NiharsWorld
    Unix
    Bash

    and file2.txt contains following lines:

    Rahin
    Unix
    Bash
    Ksh

    Find Lines in One File but not found in Other File Using fgrep – Unix Command

    fgrep -x file1.txt -v file2.txt
    

    Find Lines in One File but not found in Other File Using fgrep on Linux Command

    fgrep -x “$(< file1.txt)" -v file2.txt # content of file1 is used to create a string for -x 
    

    option.

    Explanation of above fgrep command

    – fgrep command takes all the string patterns from file1.txt and greps in file2.txt
    – -x flag option is to indicate that the whole line in file1.txt should be treated as a search pattern for grepping in file2.txt
    – -v flag option is to display only lines of file2.txt that doesn’t exist in file1.txt

    Find Lines in One File but not found in Other File Using AWK – Unix Command

    awk 'FNR==NR{a[$0];next} (!($0 in a))' file2 file1 

    Hope you were able to list contents of second file whose contents are not there in first file.

    If you know any other command, do share by leaving a comment. I would be happy to test it and include in this above post

    IMPORTANT: This blog welcomes Guest Bloggers, Writers to also contribute by writing Guest Posts and also Make Money!. Check out our Revenue Sharing Program
    1924 readers are already subscribed to this blog! Why don't you be one of them? Subscribe to this blog via your favorite RSS feed reader or by entering your email address on the form below:





    2 Comments

    1. karsten says:

      fgrep example: did not work with Linux on my computer. This worked:

      fgrep -x “$(< file1.txt)" -v file2.txt # content of file1 is used to create a string for -x option.

    Leave a Reply

    page counter
    NiharsWorld on Twitter NiharsWorld on Facebook NiharsWorld RSS Feed