Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"BEGIN blocks must have an action part" error in awk script

Tags:

bash

awk

Here is my code:

#!/bin/sh

filename=$(/usr/bin/find -name "INSTANCE-*.log")
echo "filename is " $filename

awk '
 BEGIN
 {   
   print "Processing file: " filename 
 }

 {
  if($0 ~ /Starting/) 
  { 
    print "The bill import has been Started on "$1 " " $2
  }

}'  $filename > report.txt

When I execute it I get the following error:

BEGIN blocks must have an action part

My BEGIN block has a print statement so it has an action part. What am I missing here?

like image 442
Wael Avatar asked Jan 05 '15 09:01

Wael


People also ask

Why begin is used in awk?

You generally use BEGIN and END clauses in awk when you do want certain actions before and after the actual processing on the file happens respectively. So with this logic the statements/actions within them are executed just once for the given input file.

Which block is a good place to initialize variables in the awk script?

BEGIN block This is good place to initialize variables. BEGIN is an AWK keyword and hence it must be in upper-case.

What are begin and end in awk?

A BEGIN rule is executed once only, before the first input record is read. Likewise, an END rule is executed once only, after all the input is read.


1 Answers

This happens because your opening curly brace is in the next line.

So what you need to do is to write BEGIN { ... like this:

BEGIN {
print "Processing file: " filename 
}

Note also that the main block can be rewritten to:

/Starting/ {print "The bill import has been Started on "$1 " " $2}

That is, if () and $0 are implicit so they can be skipped.

like image 65
fedorqui 'SO stop harming' Avatar answered Sep 19 '22 08:09

fedorqui 'SO stop harming'