8

I have the following code in a file named awktest1.awk:

#!/bin/awk -f
BEGIN{print "start"}
{print $2, "\t", $5}
END{print "end"} employee.txt

where employee.txt contains the following data:

100  Thomas  Manager    Sales  $5,000 
200  Jason   Developer  Technology  $5,500 
300  Sanjay  Sysadmin   Technology  $7,000 
400  Nisha   Manager    Marketing   $9,500 
500  Randy   DBA        Technology  $6,000

I run the awk command as:

awk -f awktest1.awk

but it just prints start and does not end. Can anyone help me out with what am I doing wrong here?

  • 2
    Note that by writing: print $2, "\t", $5 as opposed to print $2 "\t" $5, you're writing the 2nd field followed by OFS (space), TAB, OFS and the 5th field. – Stéphane Chazelas Aug 9 '15 at 17:21
12

The error is giving the filename to process in the script; you should remove employee.txt from the script and run it as follows

awk -f awktest1.awk employee.txt

or even, if the script is executable,

./awktest1.awk employee.txt

The script becomes

#!/bin/awk -f
BEGIN{print "start"}
{print $2, "\t", $5}
END{print "end"}

As it is, awk is waiting for input from standard input instead of reading from a file. That's why it never ends...

11

To complement @Stephen's answer, if you wanted to hardcode the name of the input file in the awk script, you'd write:

#!/bin/awk -f
BEGIN{
  ARGC=2
  ARGV[1] = "employee.txt"
  OFS = FS = "\t"
  print "start"
}
{print $2, $5}
END{print "end"}

For several files:

#!/bin/awk -f
BEGIN{
  ARGC=1
  ARGV[ARGC++] = "employee1.txt"
  ARGV[ARGC++] = "employee2.txt"
  ARGV[ARGC++] = "employee3.txt"
  # ...

  # or ARGC=1+split("employee1.txt employee2.txt employee3.txt", ARGV)

  OFS = FS = "\t"
  print "start"
}
{print $2, $5}
END{print "end"}
5

Or if you don't want to pass the filename employee.txt as a command line argument, you can do something like this:

Code:

#!/bin/awk -f
BEGIN{
    print "start"
    while((getline <"employee.txt") > 0){
        {print $2, "\t", $5}
    }
    print "end"
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.