awk Commands, Examples & Meaning

awk Built in Operational Variables

Following environmentatl variables are defined as per tghe requirment of awk program.

1. IGNORECASE=

If IGNORECASE is nonzero or non-null, then all string comparisons and all regular expression matching are case-independent.

2. OFS

The Output Field Separator . It is output between the fields printed by a print statement. Its default value is ” “, a string consisting of a single space.
localhost ~]$ awk ‘{ OFS=”|” ; print $1,$2,$3,$4}’ testfile

column1|column2|column3|column4
1111|2222|3333|4444
1111|2222|3333|4444
1111|2222|3333|4444

it can be defined by -F option also , following example define field separator as : and print first field.
awk  -F:  ‘{ print $1}’  /etc/passwd

3. ORS – Output Record Seprator

oeparator determines how records/ lines are separated default value is “\n”, the newline character.
Lets use earlier used rpms file to print lines separated by an ||  operator.

localhost ~]$ awk ‘{ ORS=”||” ; print $0}’ rpms
libhbalinux-1.0.16-2.fc20.x86_64||gucharmap-3.10.1-1.fc20.x86_64||libplist-1.11-2.fc20.x86_64||libgcc-4.8.3-7.fc20.i686||glx-utils-8.1.0-4.fc20.x86_64||vlgothic-fonts-20140801-1.fc20.noarch||

4. NF – Number of Fields, separated by space or designated by FS value

Example : count number of fields separated by :

localhost ~]$ awk -F: ‘{ print $0,NF}’ /etc/passwd
root:x:0:0:root:/root:/bin/bash 7
bin:x:1:1:bin:/bin:/sbin/nologin 7
daemon:x:2:2:daemon:/sbin:/sbin/nologin 7
adm:x:3:4:adm:/var/adm:/sbin/nologin 7
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 7
sync:x:5:0:sync:/sbin:/bin/sync 7

5. RS

The input record separator. default is a new line but can be changed to other values depending on the input file.

6. ARGC, ARGV

The command-line arguments available to awk programs are stored in an array called ARGV.

ARGC is the number of command-line arguments
ARGV is the value of argument. present and is indexed from 0 to ARGC -1
AWKPATH
awk gets its search path from the AWKPATH environment variable. If that variable does not exist, or if it has an empty value, gawk uses a default path  ‘.:/usr/local/share/awk’.

1 Comment

  1. Gabriel

    TkY! Posts like these are very useful and much appreciated by admins.

Leave a Reply

Your email address will not be published. Required fields are marked *