How to use awk to extract exact match string

How to use awk to find the exact match in a file?

test.txt hello10 hello100 hello1000 

I tried the following and returns all 3 rows

 awk '$0 ~ /^hello10/{print;}' test.txt 

grep -w hello10 does the trick, but in this window the grep version is very limited and only a few switches are available

+4
source share
5 answers

In order to fully match the regular expression, you need to bind at the beginning and end of the line with ^ and $ :

 $ awk '/^hello10$/' test.txt hello10 

But you are not using any regex functions next to the binding we just added, which means that you really want a simple string comparison:

 $ awk '$0=="hello10"' test.txt hello10 
+8
source

You can use sed command

sed -n '/\bhello10\b/p' test.txt

Here \ b indicates the border of the word you are looking for.

+1
source

You can try to use \ <\> to mark the edge of a word like \ <hello10 \>.

0
source

Your regex begins with carat ^, which binds the pattern to the beginning of the line. Try reading the awk manual page to see if you can find a way to end the template at the end of the line.

0
source

There is also the word boundary / y in gawk

awk '{if(match("hello10", sprintf("\y%s\y",$0)) print $0}' test.txt

0
source

Source: https://habr.com/ru/post/1494401/


All Articles