简体   繁体   中英

Understand a search pattern in AWK?

I am reading section 2.3 of the tutorial at - http://www.vectorsite.net/tsawk_2.html#m2

There is more to Awk's string-searching capabilities. The search can be constrained to a single field within the input line.

For example:

$1 ~ /^France$/

There is no code to which shows how this pattern works. Can someone show me how this line can be used and how it works ?

Sure!

$1 ~ /^France$/

With the following awk command:

awk '$1 ~ /^France$/ { print }'

And the following input

France 1
France1 2
france 3
- France 4
France - 5

The output will be

France 1
France - 5

$1 is the value of the first field; the default for awk is to split using whitespace delimited fields. The /^France$/ is the regular expression matching the exact string France (using start-of-string and end-of-string anchors ^ and $ ). And finally, ~ , is a binary string operator that matches the left-hand side by the regular expression on the right-hand side.

Note that regular expressions can be expressed as normal quoted strings or given in variables as well, but the "/.../" syntax is better when the expression is inline as it's more obvious and there's no need for extra escaping that strings cause when there's either a quote or a backslash in the expression.

Of course, that particular expression would be simpler as $1 == "France" .

Let me know if a more complex example will help.

To learn awk, get the book Effective Awk Programming, Third Edition By Arnold Robbins. Don't rely on random web sites to have accurate or useful information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM