awwwwkkkkkkk!!!


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting awwwwkkkkkkk!!!
# 1  
Old 05-24-2004
awwwwkkkkkkk!!!

hi everybody,
i want to know how can i do to access to the value of a variable in awk request. I explain for example:
a=2
echo "hello" |awk -F "." 'BEGIN {ORS ="\n"} { print $"$a"}'

of course it dosn t work, but how can i access to the 10th value ?
if someone has any idea, please help me.
Thank you in advance.
# 2  
Old 05-24-2004
Generally Awk does not use the '$' when accessing variable contents. It does however use the '$' for acessing field position values and special built-in variables such as NR, NF, etc. Also, to use shell variables in an Awk program you must pass them to Awk as they are not directly available. Use the -v switch to do so. $0 represents the line (record). By the way, your field separator value does not make sense for your progam as there is only 1 field and it is not delimited by anything.

Code:
a=2
echo "hello" |awk -F  "." -v a=2  'BEGIN {ORS ="\n"} { print a, $0}'

# 3  
Old 05-24-2004
hi,
if i understand i can t use an exterior variable in a awk query?
if i wan to use the second parameter of my shell script ($2) in my awk query, is it possible?
for example i want to use the length of the second parameter:
echo $2| awk '{print length($1)}' | ...
i want to use the length to read the character in that position
code
'
echo "az" | awk '{print length($1)}'

and
echo "h.ello" | awk -F "." ' {print $( the value of the previuos query )}'

how can i execute the two queries in a 1 awk query?
# 4  
Old 05-24-2004
You can use an exterior variable, using that -v option. -v a=$a would import the shell variable $a into the awk variable a.
# 5  
Old 05-24-2004
Some awks have a built-in array called ENVIRON...

$ export a=2
$ awk 'BEGIN { print ENVIRON["a"] }'
2

... but you cannot access shell positional parameters directly. Instead use something like...

$ set one two three 4 5 6 7 8 9 Ten
$ awk -v env="$*" 'BEGIN { split(env,arr); print arr[10] }'
Ten

..or perhaps...

$ awk -v a=$a -v env="$*" 'BEGIN { split(env,arr); print arr[a] }'
two

...or even...

$ awk -v a="az" -v b="h.ello" 'BEGIN { split(b,c,"."); print c[length(a)] }'
ello

Last edited by Ygor; 05-24-2004 at 10:16 AM..
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question