Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact grep -f command in Linux

I have 2 txt files in Linux.

A.txt contents (each line will contain a number):

1
2
3

B.txt contents (each line will contain a number):

1
2
3
10
20
30

grep -f A.txt B.txt results below:

1
2
3
10
20
30

Is there a way to grep in such a way I will get only the exact match, i.e. not 10, 20, 30?

Thanks in advance

like image 934
John Avatar asked May 23 '13 05:05

John


People also ask

How do I grep for an exact word in Linux?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

How do you grep an exact match?

To Show Lines That Exactly Match a Search String The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

How do I grep for exact match in bash?

Try grep " OK$" or grep "[0-9]* OK" . You want to choose a pattern that matches what you want, but won't match what you don't want. That pattern will depend upon what your whole file contents might look like.

Which grep option will look for the exact match only?

Exact Match with -w Option The -w option is used to match specified term exactly for the given content. Actually the -w option is created to match words where single word can match.


1 Answers

For exact match use -x switch

grep -x -f A.txt B.txt 

EDIT: If you don't want grep's regex capabilities and need to treat search pattern as fixed-strings then use -F switch as:

grep -xF -f A.txt B.txt
like image 99
anubhava Avatar answered Sep 22 '22 16:09

anubhava