awk

awk / nawk / gawk

Syntax

awk '/Pattern1/ {Actions}

     /Pattern2/ {Actions}' File1 File2

You can also save your awk program to a file, which can make the syntax more readable. Run it like this...

awk -f program.awk File

Examples

Field Separators and substititions

To set APXPRT to the first Port the current listener is listening on...

APXPRT=$(lsnrctl stat $LISTENER_NAME | grep PORT | head -1 | awk -F"PORT=" '{sub(/ .*/,"",$2);print $2}' | sed 's/)//g')

Explanation...

lsnrctl stat $LISTENER_NAME | grep PORT | head -1

yeilds 

  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=myhost)(PORT=1523)))

the subsequent awk command then uses -F to set the field separator to PORT=, uses sub to remove any spaces, and prints the second field. sed is then used to remove trailing parentheses, giving the result...

1523

Print field using record separators

Line in file to process...

one-two-three-four

Command we run...

cat myfile | awk -F '-' '{print $3}'

Result...

three

Print field using two record separators

Line in file to process...

<one><two><three><four>

Command we run...

cat myfile | awk -F '[>=<]' -v OFS='>' '{print $4}'

Result...

two

Real world example...

Line in file to process...

    <property name="hibernate.connection.password">password</property>

Command we run...

cat confluence.cfg.xml | grep hibernate.connection.password | awk -F '[>=<]' -v OFS='>' '{print $4}'

Result...

password

Selecting all lines between two patterns

opatch lsinventory -all | awk '/List of Oracle Homes:/,/Installed Top-level Products/'

if.. then.. else

To compare two numbers and print something based on the result...

echo ${MYFSSZ} ${fre} | awk '{ if ($1 > $2) print "*** VG too small!"; else print "*** OK"; }'

For more complex examples see:

https://www.thegeekstuff.com/2010/02/awk-conditional-statements/ 

While 

To print a line containing 50 x's...

awk 'BEGIN { while (count++<50) string=string "x"; print string }'


https://www.thegeekstuff.com/2010/02/unix-awk-do-while-for-loops/ 

Do.. While

awk 'BEGIN{count=1;do print "This gets printed at least once";while(count!=1)}'


https://www.thegeekstuff.com/2010/02/unix-awk-do-while-for-loops/ 

For...

Break

This script prints "Iteration" ten times then stops...

awk 'BEGIN{x=1;while(1){print "Iteration";if ( x==10 ) break;x++;}}'


https://www.thegeekstuff.com/2010/02/unix-awk-do-while-for-loops/ 

Continue

This script prints ten lines but skips the 5th one...

awk 'BEGIN{x=1;while(x<=10){if(x==5){x++;continue;}print "Value of x",x;x++;}}'


https://www.thegeekstuff.com/2010/02/unix-awk-do-while-for-loops/ 

Exit

This script starts to print 10 lines but exits from the loop after the 5th line...

awk 'BEGIN{x=1;while(x<=10){if(x==5){exit;}print "Value of x",x;x++;}}'


https://www.thegeekstuff.com/2010/02/unix-awk-do-while-for-loops/ 

Pruning

Shutdown...

adrci exec=show alert -p "originating_timestamp > systimestamp-1 and message_group like '%ddl%'" -term | \

   nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=1 a=0 s="^ALTER DATABASE CLOSE"

Startup...

adrci exec=show alert -p "originating_timestamp > systimestamp-1 and message_group like '%ddl%'" -term | \

   nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=1 a=0 s="^Completed: ALTER DATABASE OPEN"

Explanation

Counting fields in a file

awk -F ':' '{ total += NF }; END { print total }' /etc/passwd

Explanation

Counting lines where last field matches a pattern

awk -F ':' '$NF ~ /\/bin\/sh/ { n++ }; END { print n }' /etc/passwd

Explanation

Find line with the highest value for a field

awk -F ':'  '$3 > maxuid { maxuid=$3; maxline=$0 }; END { print maxuid, maxline }' /etc/passwd

Explanation

Print even numbered lines

awk 'NR % 2 == 0' /etc/passwd

Explanation

Find lines where fields match

awk -F ':' '$3==$4' passwd.txt

Explanation

Find lines where two conditions match

awk -F ':' '$3>=100 && $NF ~ /\/bin\/sh/' passwd.txt

Explanation

Find lines with empty fields

awk -F ':' '$5 == "" ' passwd.txt

Explanation

Remove blank lines

awk 'NF' filename

Number of lines in a file as a percentage of the number of lines in another file

echo "$(cat file1|wc -l)|$(cat file2}|wc -l)" | awk 'BEGIN { FS = "|" } { $3 = $1 / $2 * 100 "%" } { print $3 }'

Using a program file

Create a file called etc_passwd.awk...

BEGIN{

FS=":";

print "Name\tUserID\tGroupID\tHomeDirectory";

}

{

  print $1"\t"$3"\t"$4"\t"$6;

}

END {

  print NR,"Records Processed";

}

Run it using...

awk -f etc_passwd.awk /etc/passwd

Explanation

Generating HTML with awk

Operators

Built-In Variables

awk
awk

Bibliography

https://unix.stackexchange.com/questions/196058/remove-quotes-double-or-single-with-awkhttps://askubuntu.com/questions/697120/extract-word-from-string-using-grep-sed-awk https://www.shellhacks.com/sed-awk-print-lines-between-two-patterns/ https://www.thegeekstuff.com/2010/02/awk-conditional-statements/ https://www.thegeekstuff.com/2010/02/unix-awk-do-while-for-loops/ https://www.thegeekstuff.com/2011/06/awk-nawk-gawk/https://www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/https://www.thegeekstuff.com/2010/02/unix-awk-operators/https://www.thegeekstuff.com/2010/01/8-powerful-awk-built-in-variables-fs-ofs-rs-ors-nr-nf-filename-fnr/ https://www.thegeekstuff.com/2010/01/awk-tutorial-understand-awk-variables-with-3-practical-examples/ https://www.unix.com/shell-programming-and-scripting/111422-nawk-code-explanation.htmlhttps://catonmat.net/awk-one-liners-explained-part-one https://catonmat.net/awk-one-liners-explained-part-two https://catonmat.net/awk-one-liners-explained-part-three https://catonmat.net/update-on-famous-awk-one-liners-explained https://catonmat.net/awk-book https://www.unix.com/solaris/33533-grep-display-few-lines-before-after.htmlhttps://stackoverflow.com/questions/14570489/how-to-remove-blank-lines-from-a-unix-filehttps://stackoverflow.com/questions/9133315/how-can-i-output-null-terminated-strings-in-awkhttps://www.unix.com/hp-ux/278999-shell-awk-script-percentage.htmlhttps://stackoverflow.com/questions/33238089/awk-extract-string-between-two-different-patternshttps://bbs.archlinux.org/viewtopic.php?id=106924 (How to remove the newline in bash commands output)