find common elements in 2 files (for loop)

Hi,
i'm new here (and to scripting too).

I was hoping for some help in comparing two files.

i have a file called 'file1' with a list of names in the following format:
adam jones
paul higgins
kelly lowe

i also have another file which may contain some of the names but with a lot of other stuff, this is called 'file2'. it contains info such as:
aaa aaaa paul higgins aaaaa
aaaaa aaaaa aaaa aa aa aaa
aaaa aaaa kelly lowe aaaaa
asdsaad adsadsa asdas
assadasd
sa etc
(where aaaa is just random stuff html)

i want to find the common names in both files and produce an output in the form of:
0
1
1

this is with reference to the 'master' file (file1). ie. it has found in the 'file2' file that there are no adam jones, and 1 each of paul and kelly.

to do this task, i am using the following shell script however it does not seem to work:

#!/bin/sh

for i in file1

do

grep -c $i file2

done

it seems like quite a simple script, but i'm not sure why it does not work?(it only seems to grep for the first name, but does not loop through)

thanks for any help:)

Your code use "file1" as argument, not its content.
Try:

You will need to protect spaces in $line with quotation marks.

thanks!
that worked perfectly

Hi,

I have somehow similar case of question like the above with some differences.

Basically I have 2 files, file A and file B.

In file A, I have columns of fields such that:-

aaa 107
bbb 108
ccc 109

In file B, I have columns of fields such that:-
101 2 1
102 3 1
107 2 1
108 3 1
109 2 1

I would like to know, if I would like to extract let say first element of file A and compare with file B elements.

If found, I would like to have the position of element 107 in file B in this case it is on 3rd line. And the same goes for other elements in file A which in the end will pipe to another output file.

Next, I would like to get the $2 and $3 of the 3rd line for some computation.

Currently, I tried to do below:-

#!/bin/sh

for i in a.txt

do

grep -c $i b.txt

cat b.txt| awk '
{
count[$i]=$2+$3;

}
END{
printf("%d",count[$i]);
}'
done

I knew it is not going work well as the second field of A.txt is not extracted.

Please advise. Thanks.

-Jason

Hi, ahjiefreak.

It's good that you posted your scripting effort. However:

1) new problems posted in old threads often get over-looked, and some people consider it rude,

2) you've seen requests to put code tags around scripts and data,

3) you didn't post the expected output,

4) it looks like homework

Best wishes ... cheers, drl