How do I use awk to search for an exact match in a file?
test.txt
hello10
hello100
hello1000
I have tried the following and it returns all 3 lines
awk '$0 ~ /^hello10/{print;}' test.txt
grep -w hello10 does the trick but on this box grep version is very limited and only few switches available
In awk, regular expressions (regex) allow for dynamic and complex pattern definitions. You're not limited to searching for simple strings but also patterns within patterns.
Any awk expression is valid as an awk pattern. The pattern matches if the expression's value is nonzero (if a number) or non-null (if a string). The expression is reevaluated each time the rule is tested against a new input record.
More generally, you can use [[:space:]] to match a space, a tab or a newline (GNU Awk also supports \s ), and [[:blank:]] to match a space or a tab.
To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.
To do a full line regular expression match you need to anchor at the beginning and the end of the line by using ^
and $
:
$ awk '/^hello10$/' test.txt
hello10
But you're not actually using any regular expression features beside the anchoring we just added which means you actually want plain old string comparison:
$ awk '$0=="hello10"' test.txt
hello10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With