Is there a way to set a variable in my current shell from within awk
?
I'd like to do some processing on a file and print out some data; since I'll read the whole file through, I'd like to save the number of lines -- in this case, FNR
.
Happens though I can't seem to find a way to set a shell variable with FNR
value; if not this, I'd have to read the FNR
from my output file, to set, say num_lines
, with FNR
value.
I've tried some combinations using awk 'END{system(...)}'
, but could not manage it to work. Any way around this?
Passing variables from 'awk' to the shell (its parent process) can be done by 'eval'ing the 'awk' (or an entire pipleline ending with an 'awk' if desired), and having the 'awk' print text which will cause its parent shell to put the information you want into variables.
If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.
In the preceding method, variables are specified as key-value pairs, separated by a space, and (v1=$var1 v2=$var2 ) as command arguments to awk soon after the BEGIN , { } , and END ...
Here's another way.
This is especially useful when when you've got the values of your variables in a single variable and you want split them up. For example, you have a list of values from a single row in a database that you want to create variables out of.
val="hello|beautiful|world" # assume this string comes from a database query read a b c <<< $( echo ${val} | awk -F"|" '{print $1" "$2" "$3}' ) echo $a #hello echo $b #beautiful echo $c #world
We need the 'here string' i.e <<< in this case, because the read command does not read from a pipe and instead reads from stdin
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