0
#!/usr/bin/awk -f

BEGIN{
    print ARGV[1]
}
{
    print $1, $3
}
END{
    print "Done"
}

I need to have both command-line arguments and file as input. I have tried the following and got the error shown:

cat users.txt |./temp.awk 3
3
awk: ./temp.awk:4: fatal: cannot open file `3' for reading (No such file or directory)

The command-line argument is shown but i cannot seem to find a way to read the file.

Thanks.

5
  • awk is expecting a filename instead of 3. If you need to pass an argument you can use v=3 instead and drop just report the value. Commented May 12, 2020 at 20:10
  • @karakfa Can this be done without using v = 3? Thanks for your response. Commented May 12, 2020 at 20:13
  • No, otherwise awk is going to expect a filename. Only the x=y type is treated as variable decleration. Commented May 12, 2020 at 20:15
  • Put your awk script in a bash script. Commented May 12, 2020 at 20:41
  • 1
    See stackoverflow.com/a/61002754/1745001 Commented May 13, 2020 at 0:23

1 Answer 1

2

In this case, you may set ARGV[1] or ARGC inside the BEGIN block:

BEGIN {
    print ARGV[1]
    # Empty ARGV[1] so that it is not treated as a filename
    ARGV[1]=""
}
{
    print $1, $3
}
END {
    print "Done"
}

man 1p awk:

ARGC The number of elements in the ARGV array.

ARGV An array of command line arguments, excluding options and the program argument, numbered from zero to ARGC−1.

The arguments in ARGV can be modified or added to; ARGC can be altered. As each input file ends, awk shall treat the next non-null element of ARGV, up to the current value of ARGC−1, inclusive, as the name of the next input file. Thus, setting an element of ARGV to null means that it shall not be treated as an input file. The name '' indicates the standard input. If an argument matches the format of an assignment operand, this argument shall be treated as an assignment rather than a file argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.