Iceman
Iceman

Reputation: 4362

Bash - reading two files and searching within files

I have two files, file1 and file2. I want to reach each line from file1, and then search if any of the lines in file2 is present in file1. I am using the following bash script, but it does not seem to be working. What should I change? (I am new to bash scripting).

#!/bin/bash

while read line1      
do           
    echo $line1
    while read line2
    do
        if grep -Fxq "line2"  "$1"
        then 
            echo "found"
        fi
    done < "$2"             
done < "$1"

Note: Both files are text files.

Upvotes: 0

Views: 51

Answers (3)

sjsam
sjsam

Reputation: 21965

File 1

Line 1
Line 3
Line 6
Line 9

File 2

Line 3
Line 6


awk 'NR==FNR{con[$0];next} $0 in con{print $0}' file1 file2

will give you

Line 3
Line 6

that is the content in file 2 which is present in file1.

If you wish to ignore the spaces you can achieve with the below one.

awk 'NR==FNR{con[$0];next} !/^$/{$0 in con;print $0}' file1 file2

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

Use grep -f

grep -f file_with_search_words file_with_content

Note however that if file_with_search_words contains blank lines everything will be matched. But that can be easily avoided with:

grep -f <(sed '/^$/d' file_with_search_words) file_with_content

From the man page:

   -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.

Upvotes: 2

Troncador
Troncador

Reputation: 3536

You may use the command "comm", it compare two sorted files line-by-line

This command show the common lines in file1 and file2

comm -12 file1 file2

The only problem with this command is that you have to sort the files before, like this:

sort file1 > file1sorted

http://www.computerhope.com/unix/ucomm.htm

Upvotes: 0

Related Questions