So, let me know your suggestions and feedback using the comment section. Lastly I hope this tutorial to search and print exact match in Linux and Unix was helpful. The exact command may differ based on your requirement, these were some of the common use cases where you can grep exact match with some basic regex. In this tutorial I showed you multiple grep examples to match exact pattern or string using regex. Here + will match one ore more integers followed by " abcd" while ( |$) will make sure either the string is in the end of the line of has a white space character in the end Here our string contains integers, now assuming we don't know the integer values which can be there, all we know that there are some integers at the starting of " abcd" # grep -E "+abcd( |$)" /tmp/somefile Now we will try to print all the lines having 1234abcd. Method 4: Match with numbers in the string OR use /s+ to match one or more white space character while place \b at the end of the text. You could have also used: # grep -E "(\s|^)abcd(\s|$)" /tmp/somefile Here (\s|$) means, ending with white space or at the end of the line while /b is considered as word boundary and it matches the empty string at the edge of a word. With grep extended regex we can match the begin and end of the word # grep -E "\babcd(\s|$)" /tmp/somefile Method 3: Match beginning and end of word Or use " \s" instead of ( ) white space # grep -E "(^|\s)abcd(\s|$)" /tmp/somefile This gives us the perfect output of all the lines with exact " abcd" match. We can only search for exact match with leading or trailing white space characters so we know that it is exact match Method 2: Match text with white space characters If your string is in the starting then you can just use (^) # grep -E "^abcd" /tmp/somefile abcd some text
From the man page of grep: -w, -word-regexp # grep -w abcd /tmp/somefileĪs you observe, it did filtered the output by removing non-relevant match although the grep was not 100% successful. Now with grep we have an argument ( -w) which is used to grep for exact match of whole word from a file. Below is my sample file to demonstrate all the examples and scenarios from this tutorial.