It seems that awk script considers ARGV[1] to ARGV[ARGC] as input files.
Is there any way to make awk considering ARGV as simple arguments instead of an input file
Example:
test.awk
#!/usr/bin/awk -f
BEGIN {title=ARGV[2]}
{if ($1=="AA") {print title}}
dat file
AB
BA
AA
CC
$ test.awk dat 'My Interesting Title'
My Interesting Title awk: test.awk:3: fatal: cannot open file `My Interesting Title' for reading (No such file or directory)
ARGV is an array that stores all the arguments passed to the AWK command, starting from index 0 through to ARGC .
In the typical awk program, all input is read either from the standard input (by default the keyboard, but often a pipe from another command) or from files whose names you specify on the awk command line. If you specify input files, awk reads them in order, reading all the data from one before going on to the next.
The first parameter, argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. The second parameter, argv (argument vector), is an array of pointers to arrays of character objects.
Arguments given at the end of the command line to awk are generally taken as filenames that the awk script will read from. To set a variable on the command line, use -v variable=value , e.g. This would enable you to use num as a variable in your script. The initial value of the variable will be 10 in the above example.
You can modify ARGV at any time. Awk processes the elements of ARGV in turn, so if you modify them during processing, you can arrange to read different files or not to treat some arguments as file names. In particular, if you modify ARGV in the BEGIN block, anything is possible. For example, the following snippet causes awk to read from standard input even when arguments were passed, and saves the arguments in an array called args:
awk '
    BEGIN {for (i in ARGV) {args[i] = ARGV[i]; delete ARGV[i]}}
    …
' hello world
If you just want to skip the first argument, delete it only:
awk '
    BEGIN {title = ARGV[1]; delete ARGV[1]}
    $1 == "AA" {print title}
' 'My Interesting Title' input.txt
However, this is unusual and therefore may be considered hard to maintain. Consider using a shell wrapper and passing the title through an environment variable instead.
#!/bin/sh
title=$1; shift
awk '
    $1 == "AA" {print ENV["title"]}
' "$@"
You can also pass a string as an awk variable. Beware that the value undergoes backslash expansion.
awk -v 'title=My Interesting Title\nThis is a subtitle' '
    $1 == "AA" {print title}  # prints two lines!
' input.txt
Something like this?
$ awk -v title='My Interesting Title' '$0 ~ /AA/ {print title}1' input
AB
BA
My Interesting Title
AA
CC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With