""Help Me!""Beginner awk learning issue

Hi All,

I have just now started learning awk from the source - Awk - A Tutorial and Introduction - by Bruce Barnett

and the bad part is that I am stuck on the very first example for running the awk script.
The script is as -

#!/bin/sh
# Linux users have to change $8 to $9
awk '
BEGIN  { print "File\tOwner" } 
  { print $8, "\t", $3} 
END    { print " - DONE -" } 
'

However when I am saving it and running it as - "awk -f awk_example1.sh"

I am getting an error -

awk: awk_example1.sh:3: awk '
awk: awk_example1.sh:3:     ^ invalid char ''' in expression

Please can you suggest where I am getting this wrong ?
Please can anyone also suggest some good source to learn awk for a begineer ?

Thanks in advance.
Cheers!!!

How do you run the above awk script..? Try like sh awk_example1.sh where

[mkt @michael]$ cat awk_example1.sh
#!/bin/sh
# Linux users have to change $8 to $9
awk '
BEGIN  { print "File\tOwner" } 
  { print $8, "\t", $3} 
END    { print " - DONE -" } 
'
[mkt @michael]$

Also post the OS your using.

1 Like
  1. What is the input to your awk statement? $8 and $3 refer to the 8th and 3rd fields of an input. But your awk doesn't know what the input is.
  2. You've written the awk statement in a shell script yet you invoked it as an awk program.
  3. The study material you mentioned is good enough. Read once more and you'll understand.

Copy-paste this on your command line and try to understand what's happening:

ls -l | awk 'BEGIN {print "File => Owner"} {print $9, "=>", $3} END { print "- DONE -" }'

The output of 'ls -l' is sent as input to awk which prints the 9th field followed by an arrow followed by the 3rd field.

1 Like

sh awk_example1.sh worked fine and ./awk_example1.sh too worked but the output that I am getting is just as -

File    Owner

However I am having two files in current directory.

The OS that I am using is Linux.

may be you are not passing the ouput of ls -l command

$cat awk_example1.sh
#!/bin/sh
# Linux users have to change $8 to $9
ls -l | awk '
BEGIN  { print "File\tOwner" } 
  { print $8, "\t", $3} 
END    { print " - DONE -" } 
'
1 Like

Ok.Since you do not pass any input to awk statement you just get the output as File Owner . Try as suggested by itkamaraj or ls -l | ./awk_example1.sh

1 Like