Posts

Showing posts with the label awk

Part3: BEGIN and END Block in AWK

This is Part3 of the series of posts on awk utility. Part1: Introduction to AWK Part2: Regular Expressions in AWK As awk is used for reporting, one might need options to print a header or footer to the report. BEGIN and END statements allow that. BEGIN is used for declaring variables and printing banners while END is used for summaries and totals. The main block (which we have been using till now) is where the data stream (example: file or std input) is processed. In the main block, each line from the input is processed one by one, whereas the BEGIN and END blocks are procesed only once. The following example shows BEGIN block being used without main or END block. awk 'BEGIN{print "Welcome"}' Welcome In the above example, we did not pass any input. Let's look at how begin and main block are used awk 'BEGIN{print "Welcome"}{print}' Welcome Hi this is me typing Hi this is me typing In the above example, the begin block printe...

Part1: Introduction to AWK

AWK is a tool to search for a given pattern and perform specific actions on it. Syntax: awk <options> ' <address> { <actions> }' <input|file(s)> Examples: awk '{print $0}' hi this is a test hi this is a test ^d awk '{print $1, $4}' hi this is a test hi a ^d awk '{print $1, $4}' hi how hi are are you you ^d In the above examples, we did not mention the input explicitly. The input provided on the terminal is used for performing the print action. {print $0} prints the entire line and {print $1, $4} prints the 1st and 4th word in the input. Let's see how input can be passed though a file . echo hi how are you > awk.input awk '{ print $0 } ' awk.input hi how are you awk '{ print "sapnwnewbie: ", $2, $3, $4 } ' awk.input sapnwnewbie:  how are you In all the above examples, we used the default seperator--space. Let's look at an example where we use colon (:) as se...