All of my codes fail. They should print "he", "hello" and "5 \n 3", respectively:
awk -v e='he' {print $e} // not working, why?
awk NF { print hello }
awk { print ARGV[5,3] }
Are there some simple examples about AWK?
All of my codes fail. They should print "he", "hello" and "5 \n 3", respectively:
awk -v e='he' {print $e} // not working, why?
awk NF { print hello }
awk { print ARGV[5,3] }
Are there some simple examples about AWK?
For the first, you don't use $ for variables inside awk, try this instead:
fury> echo | awk -v e='he' '{print e}'
he
For the second, your condition NF means NF!=0 so it will only print for non empty lines:
fury> echo | awk 'NF {print "hello"}'
fury> echo "7 8" | awk 'NF {print "hello"}'
hello
I've never seen your syntax for the third one, ARGV is a single dimensional array, so you can use:
fury> awk 'BEGIN {print ARGV[5]}' 1 2 3 4 5 6 7
5
fury> awk 'BEGIN {print ARGV[5] "\n" ARGV[3]}' 1 2 3 4 5 6 7
5
3
Note I'm using a BEGIN block for the third, otherwise it'll try to open and process 1, 2, 3, ... as files.
Try:
echo "hello" | awk ' {print $0} '
echo "hello" | awk ' {print $1} '
Note that $0 returns the whole record, and $1 just the first entry; awk starts its counters at 1. So
echo "hello1 hello2 hello3" | awk ' {print $0} '
returns hello1 hello2 hello3. While
echo "hello1 hello2 hello3" | awk ' {print $3} '
will return hello3
I like this awk tutorial.
First, basic shell scripting sanity:
Note that the script is a single argument - or a filename with '-f file
'.
An awk script is a sequence of '<pattern> <action>
' pairs. The action is enclosed in braces '{}
' for clarity - and sanity, again.
As Pax said, the first example should be:
awk -v -e e='he' '{ print e }'
The second example is inscrutable - you probably meant:
awk '{ print "hello" }'
The variable NF is the number of fields on the line. You might get awk to interpret
awk 'NF { print "hello" }'
as if there is any data on the input line (NF != 0, or number of fields is not zero), then print 'hello'.
The last example is likewise inscrutable; ARGV is an array of the arguments to 'awk', and the command line provided none. But it is a one-dimensional array. Your sub-scripting notation wants to treat it like a Python dictionary or Perl hash, with two indexes combined. You're OK - awk supports associative arrays; but since you didn't add anything to the array at ARGV[5,2], it won't print anything.