Question: I'm reading a string from file, appliances\_list.txt. 

appliances\_list.txt contains

```
fridge
dryer
ironbox
microwave 

```

The file I'm reading is myappliances.txt. Content is

```
I have a fridge
I have another fridge
I have a refridgerator
I have a microwave
I have ironbox at home
I have another microwave
I have a hairdryer

```

I'm using 

```
grep -o -m1 -f appliances_list.txt myappliances.txt

```

Output is 

`fridge`

My desired output is, first occurrence of each string (exact match)

```
fridge
microwave
ironbox

```

Can someone point me in the right direction?

Answer: 
```
$ cat tst.awk
NR==FNR { strings[$0]; ++numStrings; next }
{
    for (i=1;i<=NF;i++) {
        if ($i in strings) {
            print $i
            delete strings[$i]
            if (--numStrings == 0) {
                exit
            }
            break
        }
    }
}

$ awk -f tst.awk appliances_list.txt myappliances.txt
fridge
microwave
ironbox

```

That will be very efficient since it will remove each found string from the list of strings as it's found so there's fewer comparisons necessary on every line and when there's no more strings in the list will exit the program so it doesn't waste time reading the remaining lines of the 2nd file.
Modify your code as following. This would work very efficiently (considering your filesize is 2GB)

```
while read -r appliance; do grep -m1 -ow $appliance myappliances.txt;done<appliances_list.txt

```

`-w`: for exact word match

Output:

```
fridge
ironbox
microwave

```

Explanation:  

Firstly,in your code, the `-m1` is causing to stop matching once first match is found and it stops reading the file causing the program to exit.

What you have to do is iterate over file1 and for each word in it grep over file2 and use your logic.

Other solution is :

Use **head -1** along with grep to stop searching after first match is found. 

```
while read -r appliance; do grep -ow $appliance myappliances.txt | head -1; done<appliances_list.txt

```