user3624000
user3624000

Reputation: 311

Matching the string in a File using IF

I am trying a find a strings of a file matching with another file and collecting them into an array. As a first step, I tried to find a string matching of two files. I used below code, but strangely I am getting this message grep: 3: No such file or directory,grep: 5: No such file or directory. I could not figure out the rootcause for this. Can some one help me finding the rootcause? Shell script used:

#!/bin/bash
while
read LINE
do
if grep -q $LINE /tmp/UA_Automation/glhard; then
echo "$LINE"
echo "matched"
else
echo "$LINE"
echo "not_matching"
fi
done < /tmp/UA_Automation/UA_daily_listings_unique_count.csv|awk '{ print $1 }'

glhard & UA_daily_listings_unique_count.csv are name of the file. Contents of these two files respectively are:

glauto
gltyre
gldisc
glclothes    


glwheel 2
glgun 3
glauto 4
gldisc 4
glpants 6

Can someone help me figure out this?

Upvotes: 0

Views: 64

Answers (2)

Barmar
Barmar

Reputation: 780851

You're piping the output of the loop to awk. You want to go the other way:

awk '{print $1}' /tmp/UA_Automation/UA_daily_listings_unique_count.csv | while read LINE
do
    if grep -q $LINE /tmp/UA_Automation/glhard; then
        echo "$LINE"
        echo "matched"
    else
        echo "$LINE"
        echo "not_matching"
    fi
done

Although you could also make use of read splitting the line:

while read LINE NUMBER
do 
    ...
done < /tmp/UA_Automation/UA_daily_listings_unique_count.csv

Upvotes: 1

chepner
chepner

Reputation: 531055

The value of LINE contains whitespace; you need to quote it so that the entire value is used as the pattern, not just the first word after word-splitting.

if grep -q "$LINE" /tmp/UA_Automation/glhard; then

That said, I'd recommend looking at diff or comm for such line-by-line comparisons of files, rather than running grep for each line.

Upvotes: 1

Related Questions