argc/ argv in awk

Hi guys,

i'm trying to solve this problem.
I have to run something like

cat file1.txt | awk -f script.awk 10

if i'm in the awk script, how can i take the parameter :10 ??:wall:

i try something like :

BEGIN{
var=argv[6]
}

{..}

END{..}

but obviously is not correct...

ty in advance

You get a useless use of cat award.

Fortunately you don't need to specify 'parameter 2' or anything. You can set variables directly, with the -v parameter.

awk -v VAR=10 -v ANOTHERVAR=42 -f script.awk file1.txt
1 Like

Ty Corona for your answer, but I know the -v option.

Unfortunately, i need to do like what i wrote before, sure it is very easy but i dont find the way..i'll try also
argv in upper case

var=ARGV[6]

but nothing..

awk doesn't work that way. Giving awk an argument of '10' tells it to open a file named '10'. Positional parameters are arguments or filenames, period.

If ARGV[1] doesn't work in your awk, then your awk doesn't have ARGV.

Why do you need this? Couldn't you make a simple wrapper script to do this for you, converting shell arguments into a -v argument, instead of cramming arguments where they don't belong on awk's commandline?

This is a real good question. :b::b:

I had a test yesterday and one of the question was: "Write an awk script that simulate the bash command tail, where the number of lines to print is give as:
cat file.txt | awk -f script.awk 10
"

wtf... :smiley:

That's a particularly awful way to do it since it will fail instantly, trying to open the file '10'. You'll have to cram everything into awk's BEGIN section, and exit at the end of it, so it doesn't try to open a file named 10. You'd do a while(getline<"/dev/stdin") loop. ARGV[3] would be the number of lines if your particular version of awk even has ARGV.

tail is not a "bash command", either. bash has some builtins and tail is not one of them. tail is an external utility that can be used with any shell or with no shell at all. It has nothing to do with bash whatsoever. This is an increasingly common and most vexing misconception because people keep trying to fix bash when the problem is not having installed the thing they're looking for in the first place :wall:

And of course that remains a useless use of cat. I've been wondering who keeps teaching this to people. :wall:

1 Like