0

This is my shell script that receives a string as an input from the user from the stdin.

#!bin/sh
printf "Enter your query\n"

read query
cmd=`echo $query | cut -f 1 -d " "`
input_file=`echo $query | cut -f 2 -d " "`
printf $input_file

if [ $input_file = "" ]
then
    printf "No input file specified\n"
    exit
fi
if [ $cmd = "summary" ]
then
    awk -f summary.awk $input_file $query
fi

Lets say he enters

summary a.txt /o foo.txt

Now cmd variable will take the value summary and input_file will take a.txt. Isn't that right?

I want summary.awk to work on $input_file, based on what is present in $query.

My understanding is as follows :

  1. The 1st command line argument passed is treated as input file. e.g. : awk 'code' file arg1 arg2 arg3 only file is treated as input file

  2. If the input file is piped, it doesn't see any of the arguments as input files. e.g. : cat file | awk 'code' arg1 arg2 arg3 arg1 is NOT treated as input file.

Am I right?

The problem is I get awk: cannot open summary (No such file or directory) Why is it trying to open summary? It is the next word after $input_file.

How do I fix this issue?

batman
  • 5,022
  • 11
  • 52
  • 82

1 Answers1

3

If there's no -f option, the first non-option argument is treated as the script, and the remaining arguments are input files. If there's a -f option, the script comes from that file, and the rest are input files.

If and only if there are no input file arguments, it reads the input from stdin. This means if you pipe to awk and also give it filename arguments, it will ignore the pipe.

This is the same as most Unix file-processing commands.

Try this:

awk -f summary.awk -v query="$query" "$input_file"

This will set the awk variable query to the contents of query.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • So, the right way to pass data to an awk script is to use the -v option? Otherwise the passed args will necessarily be considered as input files to be iterated over? – batman Nov 12 '12 at 11:18
  • Yes. I think you can read and assign to `ARGV` in the script to remove input files, but that's not the best way to do what you want. – Barmar Nov 12 '12 at 11:19
  • I tried printing `query` in my awk script. It says : `illegal reference to variable query`. And do we have to use double quotes around `$query` or anything like that? I mean, it's still in the shell script file, so, do we have to? – batman Nov 12 '12 at 11:27
  • You need the double quotes in the shell script, but not in `summary.awk`. – Barmar Nov 12 '12 at 11:31
  • There was a variable named `query` in the awk file. That was the problem. Sorry. But I just tried this out : `awk 'BEGIN {print query}' -v query="$query" "$input_file"` `awk 'BEGIN {print FILENAME}' -v query="$query" "$input_file"` Both of them print empty lines. – batman Nov 12 '12 at 11:47
  • I've had it resolved. Apparently inside BEGIN, it doesn't have `FILENAME` ready yet. Thanks! – batman Nov 12 '12 at 12:39