For Programmers: Free Programming Magazines  


Home > Archive > AWK > December 2006 > Assigning a field variable in awk program to a shell variable









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Assigning a field variable in awk program to a shell variable
deeplights@gmail.com

2006-12-11, 7:00 pm

hi
myself a newbie to unix shell scripting and stuff..
i want to assign a field variable in an awk program to a shell
variable.
like for eg
if shell_var is one of a shell variable
then i want to assign the line numbers returned by the grep command
with -n option
to a shell variable.

the code that i've tried is this
grep -n string filename | awk -F : '{shell_var = $1}'

it doesn't work

please help..

Janis Papanagnou

2006-12-11, 7:00 pm

deeplights@gmail.com wrote:
> hi
> myself a newbie to unix shell scripting and stuff..
> i want to assign a field variable in an awk program to a shell
> variable.
> like for eg
> if shell_var is one of a shell variable
> then i want to assign the line numbers returned by the grep command
> with -n option
> to a shell variable.
>
> the code that i've tried is this
> grep -n string filename | awk -F : '{shell_var = $1}'


First, you don't need grep if you use awk. The above can be written as

awk '/string/ {shell_var = NR}' filename

but here 'shell_var' is an awk variable.

>
> it doesn't work


Now to make the above work

shell_var=$( awk '/string/{print NR; exit}' filename )

I added 'exit' because you just want a single line number in the shell
variable.

Janis


>
> please help..
>

Ed Morton

2006-12-11, 7:00 pm

Janis Papanagnou wrote:
> deeplights@gmail.com wrote:
>
>
>
> First, you don't need grep if you use awk. The above can be written as
>
> awk '/string/ {shell_var = NR}' filename
>
> but here 'shell_var' is an awk variable.
>
>
>
> Now to make the above work
>
> shell_var=$( awk '/string/{print NR; exit}' filename )
>
> I added 'exit' because you just want a single line number in the shell
> variable.
>
> Janis


And if you want to pass the value of a shell variable to an awk script
in future, see question 24 in the comp.unix.shell FAQ
(http://home.comcast.net/~j.p.h/cus-faq-2.html#24).

Ed.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com