Gnu awk

Introduction

The name awk comes from the initials of its designers: Alfred V. Aho, Peter J. Weinberger and Brian W. Kernighan. The original version of awk was written in 1977 at AT&T Bell Laboratories.

References:

Passing parameters to awk in a shell wrapper

Passing parameters to awk is tricky, depending on what you want to do. If you use getline, resetting ARGC to 1 will work as expected, otherwise awk responds with something like "/usr/local/bin/myscript:131: fatal: cannot open file 'x' for reading (No such file or directory)" where the referenced line seems arbitrary but will point to the first getline. For example,

#!/usr/bin/awk -f
BEGIN {
  if(ARGV[1] = "d") debug=1
  ...
}
if (debug){
  do this
  do that
  getline
}


The line number will point to the getline because awk is trying to read from the file pointed to by ARGV[1]

One solution is to reset ARGC

#!/usr/bin/awk -f
BEGIN {
  if(ARGV[1] = "d"){
    debug=1
    ARGC = 1
  }
  ...
}
if (debug){
  do this
  do that
  getline
}

True and False

In awk, any nonzero numeric value or any nonempty string value is true. Any other value (zero or the null string "") is false.

Concatenation

The string concatenation operator is a space

group = "is the time"
print "now " group

Prints now is the time

Control statements

Using switch

Note: Must be compiled with --enable-switch
Note: like C, uses fall through.

switch (expression) {
  case value|regex : statement
  ...
  [ default: statement ]
}

Passing an array to a function

Also shows ternary operator and use of gensub to delete from a string

function rm(char,array,r,c){
  # remove char from array[r,c]. If none left, make it 0
  array[r,c] = (array[r,c] == char ? 0 : gensub(char,"",1,array[r,c]))
}

Arrays are passed by reference. Scalars are passed by value. Everything is global unless placed in the parameter list as extra parameters.

function foo(a,b,c, d,e,f){
  # a, b, and c are parameters
  # d, e, and f are local to the function
  # the convention is to set the local variables off by using spaces
  ...
}

Using gensub, gsub, and sub

gensub returns the string, gsub and sub return the number of substitutions. This makes these functions useful for doing things like counting things in a string.

foo = "10390506630"


How many zeroes ?

print gsub(0, 0, foo)

Prints 4

Also to remove things. Remove the zeros

bar = gensub(/0/,"","g",foo)
print bar


Prints 1395663

Remove the first zero

sub(/0/,"",foo)
print foo


Prints 1390506630

Remember - gensub returns the new string without modifying the original.
gsub and sub modify the original string and return the number of substitutions made.


Send mail to the Webmaster

logo This site best viewed with a browser
Warning: This is a Debian centric site
Many thanks to Debra and Ian Murdock for making Debian possible
First created Jan 25, 2010 ~ Last revised February 06, 2010

Valid XHTML 1.0 Strict Valid CSS!