Using shell variables in awk

It is possible to use shell variables within a awk command in a shell script.
As mentioned in the GNU Awk official documentation, one use case is that the shell variable holds the pattern that will be used by awk.
Here is one of the given examples :


printf "Enter search pattern: "
read pattern
awk -v pat="$pattern" '$0 ~ pat { nmatches++ }
END { print nmatches, "found" }' /path/to/data

If the pattern search is a bit more complicated than the one below $0 ~ pat, then this feature does not work anymore.

More details :

AWK : Using Shell Variables in Programs

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.