[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Importing Shell Variables in to awk from Shell Scripts



Martin McCormick <martin@dc.cis.okstate.edu> writes:

> 	I have a shell script that is supposed to search a file of
> text and, if the sixth field in a line matches a search string, print
> the whole line.  This seems like a good job for awk and, after some
> searching, I found that you can import variables in to awk something
> like:
>
> awk '(/'"$searchvar"'/ == $6) {print $0}' "$inputfile"
>
> 	The problem is while the awk script runs, the results are
> either the entire text file if I use a begin block
>
> awk 'begin {(/'"$searchvar"'/ == $6)} {print $0}' "$inputfile"
>
> 	Or it is truncated if the first example is used and one gets a
> large portion but not the entire text file spewed out.  In neither
> case does any testing appear to be happening to see if $searchvar
> matches $6.
>
> 	If the parentheses are removed, you get the whole input file
> sent to the output, again with no testing.
>
> 	Thanks for any ideas on other syntax to try.  Some would do
> this in perl, but awk should do this job.

The last point applies, because it's not about importing shell
vars, but your awk syntax is wrong. Your first example is almost
correct, though. Just decide whether you want string comparison
or regex match:

awk '($6 == "'"$searchvar"'") {print $0}' "$inputfile"
awk '($6 ~ /'"$searchvar"'/) {print $0}' "$inputfile"

man awk is a good reference, btw.

Regards, Bruno.



Reply to: