Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash text search: find if the content of one file exists in another file [closed]

Tags:

bash

shell

Say we have two files: a.txt and b.txt. Each file has multiple lines of text.

How do I write a shell script to check if all of the content of a.txt exists in b.txt?


Thx for the hints guys, i didn't noticed -q will output 0 if successfully matched.

I end up with:

if grep a.txt -q -f b.txt ; then

else

fi

like image 312
Jinglue Li Avatar asked Jan 15 '14 03:01

Jinglue Li


3 Answers

try grep

cat b.txt|grep -f a.txt
like image 160
orange Avatar answered Oct 07 '22 08:10

orange


Here is a script that will do what what you are describing:

run: sh SCRIPT.sh a.txt b.txt

# USAGE:   sh SCRIPT.sh TEST_FILE CHECK_FILE
TEST_FILE=$1
CHECK_FILE=$2

## for each line in TEST_FILE
while read line ; do

    ## check if line exist in CHECK_FILE; then assign result to variable
    X=$(grep "^${line}$" ${CHECK_FILE})


    ## if variable is blank (meaning TEST_FILE line not found in CHECK_FILE)
    ## print 'false' and exit
    if [[ -z $X ]] ; then
        echo "false"
        exit
    fi

done < ${TEST_FILE}

## if script does not exit after going through each line in TEST_FILE,
## then script will print true
echo "true"

Assumptions:

  • line order from a.txt does not matter
like image 30
csiu Avatar answered Oct 07 '22 07:10

csiu


Using grep

grep -f a.txt b.txt
like image 2
BMW Avatar answered Oct 07 '22 08:10

BMW