Tuesday, September 13, 2011

awk - Passing arguments or shell variables to awk



  In one of our earlier articles, we saw how to read a file in awk. At times, we might have some requirements wherein we need to pass some arguments to the awk program or to access a shell variable or an environment variable inside awk. Let us see in this article how to pass and access arguments in awk:

Let us take a sample file with contents, and a variable "x":
$ cat file1
24
12
34
45
$ echo $x
3
Now, say we want to add every value with the shell variable x.


1.awk provides a "-v" option to pass arguments. Using this, we can pass the shell variable to it.
$ awk -v val=$x '{print $0+val}' file1
27
15
37
48
  As seen above, the shell variable $x is assigned to the awk variable "val". This variable "val" can directly be accessed in awk.

2. awk provides another way of passing argument to awk without using -v. Just before specifying the file name to awk, provide the shell variable assignments to awk variables as shown below:
$ awk  '{print $0,val}' OFS=, val=$x file1
24,3
12,3
34,3
45,3
3. How to access environment variables in awk? Unlike shell variables, awk provides a way to access the environment variables without passing it as above. awk has a special variable ENVIRON which does the needful.
$ echo $x
3
$ export x
$ awk  '{print $0,ENVIRON["x"]}' OFS=,  file1
24,3
12,3
34,3
45,3

Quoting file content:

  Some times we might have a requirement wherein we have to quote the file contents. Assume, you have a file which contains the list of database tables. And for your requirement, you need to quote the file contents:
$ cat file
CUSTOMER
BILL
ACCOUNT

4. Pass a variable to awk which contains the double quote. Print the quote, line, quote.
$ awk -v q="'" '{print q $0 q}' file
'CUSTOMER'
'BILL'
'ACCOUNT'
5. Similarly, to double quote the contents, pass the variable within single quotes:
$ awk '{print q $0 q}' q='"' file
"CUSTOMER"
"BILL"
"ACCOUNT"

4 comments:

  1. i really like your awk tutorials their straight forward

    ReplyDelete
  2. This is simple and great tutorial

    ReplyDelete
  3. Tutorial is very good, pretty easy to understand as it is explained very nicely with examples.

    ReplyDelete