Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use awk to extract a line with exact match

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

like image 908
Mark T Avatar asked Jul 31 '13 02:07

Mark T


People also ask

Does awk support regex?

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.

What is pattern matching in awk?

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.

How do you match space in awk?

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.

How do we print report with awk programming?

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.


1 Answers

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
like image 134
Chris Seymour Avatar answered Sep 23 '22 15:09

Chris Seymour