Sponsored Content
Top Forums Shell Programming and Scripting Begin/End blocks in awk: confused Post 302882406 by RudiC on Monday 6th of January 2014 04:49:00 PM
Old 01-06-2014
awk takes a set of files as arguments, which altogether present a stream of lines to it. Line after line is processed, with the internal FILENAME variable changing if need be (if switching to the next file).
Before any of the lines of the stream is read, ALL of the BEGIN actions are being processed. You can use this to initialize variables, print headers, what have you.
After the last line of the entire stream, possibly consisting of many a file, ALL the END actions will be processed, e.g. for printing totals. That means, you can calculate your count[$2]++ during normal processing, and at the END, print out (in whatever structure) what you have computed so far.
And it looks to me as if that's exactly what that code snippet you presented is doing...
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

BEGIN END questions

Why would you need to use this in a script? Why can't you just use print to print out what you want printed in the begining and print for what you want at the end. So this: nawk 'BEGIN {print "this is the first line"} {print $1 $2 $3} {print $5 $6} END {print "this is the last line"}' ... (2 Replies)
Discussion started by: llsmr777
2 Replies

2. Shell Programming and Scripting

begin end detection

Hi all, i am new to scripting. i need to write a code to detect begin and end of word that either begins or ends with t,th,d,dh,s,sh i have a set of words in a file containg one word per line. let the filename be aaa.txt. i have an another file bbb.txt which has two lines, just specifying the... (7 Replies)
Discussion started by: blkanth
7 Replies

3. Shell Programming and Scripting

awk BEGIN END and string matching problem

Hi, Contents of BBS-list file: foo foo foo awk ' BEGIN { print "Analysis of \"foo\"" } /foo/ { ++n } END { print "\"foo\" appears", n, "times." }' BBS-list Output: Analysis of "foo" "foo" appears 3 times. awk ' (3 Replies)
Discussion started by: cola
3 Replies

4. Shell Programming and Scripting

Use of Begin IF ,END IF END not working in the sql script

Hi I have written a script .The script runs properly if i write sql queries .But if i use PLSQL commands of BEGIN if end if , end ,then on running the script the comamds are getting printed on the prompt . Ex :temp.sql After connecting to the databse at the sql prompt i type... (1 Reply)
Discussion started by: isha_1
1 Replies

5. UNIX for Dummies Questions & Answers

Dump to another file for a begin and end Pattern

Hi All , I am newbie to linux shell scripting , below are the contents of my log file , i want the lines between a begin pattern and a end pattern for an instance , my begin Pattern is "Transaction Begins for Usr" and end pattern is "Transaction Ends for Usr" into another file Sample file... (1 Reply)
Discussion started by: SARAVANANE
1 Replies

6. Shell Programming and Scripting

strange: sed and awk print at end instead of begin of line

Hi! I have a strange behaviour from sed and awk, but I'm not sure, if I'm doing something wrong: I have a list of words, where I want to add the following string at the end of each line: \;\;\;\;0\;1 I try like this: $ cat myfile | awk '{if ( $0 != "" ) print $0"\;\;\;\;0\;1"}' Result:... (5 Replies)
Discussion started by: regisl67
5 Replies

7. Shell Programming and Scripting

Get the sum of values in between begin and end in the file

Hi All, test file Begin Script Run at Thu Mar 14 09:24:16 PDT 2013 tst_accounts: ws zip: WS_out_20130313.tar.gz dat: test_20130313.dat count: 63574 loaded: xx pre-merge: xx post-merge: xx timestamp: Thu Mar 14 09:30:42 PDT 2013 tst_accounts: ws zip: WS_out_20130313.tar.gz dat: s_20130313.dat... (6 Replies)
Discussion started by: bmk
6 Replies

8. Shell Programming and Scripting

BEGIN and END format in awk

I'm new to awk, trying to understand the basics. I'm trying to reset the counter everytime the program gets a new file to check. I figured in the BEGIN part it would work, but it doesn't. #!/bin/awk -f BEGIN {counter=0} { sum=0 for ( i=1; i<=NF;... (1 Reply)
Discussion started by: guitarist684
1 Replies

9. Shell Programming and Scripting

Search ad replace using begin and end of the file

Hello Friends , Please help to create script for compare and replace if not matches of set of lines . * Primary* Servername Server1 Location R201 Rack 4 *End Primary* *Secondary* Server Name Server1 IPAddress 10.24.30.10 Application Apache *End of Secondary* Above... (4 Replies)
Discussion started by: rnary
4 Replies

10. Shell Programming and Scripting

In ksh script what is this BEGIN and END in this function?

Can Someone please explain why BEGIN and END statement is used inside function? How does that help in scripting? function fileformatting { CleanupMask="xXxX" sed 's/^.//' < ${AllFile} > ${AllFile}.tmp echo $(wc -l ${AllFile}.tmp) `awk -v CleanupMask=${CleanupMask} ' BEGIN... (2 Replies)
Discussion started by: later_troy
2 Replies
AWK  is  a  programming  language devised by Aho, Weinberger, and
Kernighan at Bell Labs (hence the  name).   Awk  programs  search
files for specific patterns and performs actions for every occur-
rence of these patterns.  The patterns can be regular expressions
as used in the ed editor.  The actions are expressed using a sub-
set of the C language.	The  patterns  and  actions  are  usually
placed	in  a rules file whose name must be the first argument in
the command line, preceded by the flag -f.  Otherwise, the  first
argument  on  the command line is taken to be a string containing
the rules themselves. All other arguments are  taken  to  be  the
names  of text files on which the rules are to be applied, with -
being the standard input.  To take rules from the standard input,
use -f -.  The command: would read the patterns and actions rules
from the file rules and apply them to  all  the  arguments.   The
general  format  of  a	rules  file is: ~~~<pattern> { <action> }
~~~<pattern> { <action> } ~~~...  There  may  be  any  number  of
these  <;pattern>  {  <action> } sequences in the rules file.  Awk
reads a line of input from the current input file and applies ev-
ery <;pattern> { <action> } in sequence to the line.  If the <pat-
tern>; corresponding to any { <action> } is missing, the action is
applied  to  every line of input.  The default { <action> } is to
print the matched input line.  The <;pattern>s may consist of  any
valid C expression.  If the <;pattern> consists of two expressions
separated by a comma, it is taken to be a range and the  <;action>
is  performed  on all lines of input that match the range.  <;pat-
tern>;s may contain regular expressions delimited by an @  symbol.
Regular  expressions  can be thought of as a generalized wildcard
string matching mechanism, similar to that used by many operating
systems  to  specify file names.  Regular expressions may contain
any of the following characters:
  x    An ordinary character
      The backslash quotes any character
  ^    A circumflex at the beginning of an expr matches  the  be-
       ginning of a line.
  $    A  dollar-sign at the end of an expression matches the end
       of a line.
  .    A period matches any single character except newline.
  *    An expression followed by an asterisk matches zero or more
       occurrences  of	that  expression: fo* matches f, fo, foo,
       fooo, etc.
  +    An expression followed by a plus sign matches one or  more
       occurrences of that expression: fo+ matches fo, foo, fooo,
       etc.
  []   A string enclosed in square brackets  matches  any  single
       character  in  that  string,  but no others.  If the first
       character in the string is a  circumflex,  the  expression
       matches any character except newline and the characters in
       the string.  For example, [xyz] matches xx and zyx,  while
       [^xyz] matches abc but not axb.	A range of characters may
       be specified by two characters separated by -.
Actions are expressed as a subset of the C language.   All  vari-
ables  are  global and default to int's if not formally declared.
Only char's and int's and pointers and arrays of char and int are
allowed.   Awk allows only decimal integer constants to be used--
no hex (0xnn) or octal (0nn). String and character constants  may
contain  all  of  the special C escapes (
, 
, etc.).  Awk sup-
ports the if, else, while and break flow of  control  constructs,
which  behave  exactly as in C.  Also supported are the following
unary and binary operators, listed in order from highest to  low-
est precedence:
  Operator	 Type	      Associativity
  () [] 	 unary	      left to right
  ! ~ ++ -- - * &	      unaryright to left
  * / % 	 binary       left to right
  + -		 binary       left to right
  << >> 	 binary       left to right
  < <= > >=	 binary       left to right
  == != 	 binary       left to right
  &		 binary       left to right
  ^		 binary       left to right
  |		 binary       left to right
  &&		 binary       left to right
  ||		 binary       left to right
  =		 binary       right to left
Comments are introduced by a '#' symbol and are terminated by the
first newline character.  The standard /* and */  comment  delim-
iters  are not supported and will result in a syntax error.  When
awk reads a line from the current input file, the record is auto-
matically  separated  into fields.  A field is simply a string of
consecutive characters delimited by either the beginning  or  end
of  line,  or  a field separator character.  Initially, the field
separators are the space and tab character.   The  special  unary
operator  '$'  is used to reference one of the fields in the cur-
rent input record (line).  The fields are  numbered  sequentially
starting  at  1.   The	expression $0 references the entire input
line.  Similarly, the record separator is used to  determine  the
end of an input line, initially the newline character.	The field
and record separators may be changed programatically  by  one  of
the  actions and will remain in effect until changed again.  Mul-
tiple (up to 10) field separators are allowed at a time, but only
one  record  separator.   Fields behave exactly like strings; and
can be used in the same context as a character array.  These  ar-
rays  can be considered to have been declared as:      char ($n)[
128 ]; In other words, they are 128 bytes long.  Notice that  the
parentheses  are  necessary  because the operators [] and $ asso-
ciate from right to left; without them, the statement would  have
parsed	as:	 char $(1[ 128 ]); which is obviously ridiculous.
If the contents of one of these field arrays is altered,  the  $0
field  will  reflect  this change.  For example, this expression:
     *$4 = 'A'; will change the first  character  of  the  fourth
field to an upper- case letter 'A'.  Then, when the following in-
put line:      120 PRINT  "Name 	 address	 Zip"  is
processed,   it   would  be  printed  as:	120  PRINT  "Name
Address        Zip"; Fields may also be modified with the strcpy()
function  (see below).	For example, the expression:	  strcpy(
$4, "Addr." ); applied	to  the  same  line  above  would  yield:
     120  PRINT  "Name		Addr.	      Zip"  The following
variables are pre-defined:
   FS	       Field separator (see below).
   RS	       Record separator (see below also).
   NF	       Number of fields in current input record (line).
   NR	       Number of records processed thus far.
   FILENAME    Name of current input file.
   BEGIN       A special <pattern> that matches the beginning  of
	       input text.
   END	       A  special <pattern> that matches the end of input
	       text.
Awk also provides some useful built-in functions for  string  ma-
nipulation and printing:
   print(arg)  Simple  printing  of  strings  only, terminated by
	       '
'.
   printf(arg...)Exactly the printf() function from C.
   getline()   Reads the next record and  returns  0  on  end  of
	       file.
   nextfile()  Closes  the current input file and begins process-
	       ing the next file
   strlen(s)   Returns the length of its string argument.
   strcpy(s,t) Copies the string t to the string s.
   strcmp(s,t) Compares the s to t and returns 0 if they match.
   toupper(c)  Returns its character argument converted to upper-
	       case.
   tolower(c)  Returns its character argument converted to lower-
	       case.
   match(s,@re@)Compares the string s to the  regular  expression
	       re  and	returns the number of matches found (zero
	       if none).
Awk was written by Saeko Hirabauashi and Kouichi Hirabayashi.
All times are GMT -4. The time now is 11:00 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy