简体   繁体   中英

Exporting awk variables to bash variables?

I want to save some of the values which I calculate while processing a textfile with awk to a bash variable. For example if my file.txt have the following

total 16  
dr-xr-xr-x  18 root root  257 Mar 26 16:24 .  
dr-xr-xr-x  18 root root  257 Mar 26 16:24 ..  
-rw-r--r--   1 root root    0 Mar 24 22:23 .autorelabel   
lrwxrwxrwx   1 root root    7 Mar 18 08:15 bin -> usr/bin  
dr-xr-xr-x   4 root root 4096 May 20 17:05 boot  
drwxr-xr-x  14 root root 2860 Apr 17 03:09 dev  
drwxr-xr-x  95 root root 8192 May 20 17:05 etc  

and if I want to calculate the sum of the fifth column and the number of hide files I would do

awk 'NR>1 {sum+=$5; if(substr($9,1,1)=="."){count+=1}} END{print "The disk space is " sum " and the number of hidden files is " count}' file.txt  

Output

The disk space is 15669 and the number of hidden files is 3

and what I want to do is save the variables sum and count for later use in my script without having to make each calculation again, for example like doing SUM=$(awk '{sum+=$5} END{print sum}' file.txt)

I know you can pass bash variables to awk using the -v option but I want to do the inverse, something like "{export SUM=sum}" within awk.

You can read from the output of a process substitution:

read sum count < <(
    awk '
        NR > 1 {sum += $5; if (substr($9,1,1) == ".") count++}
        END {print sum, count}
    ' file.txt
)

With respect to I know you can pass bash variables to awk using the -v option - not exactly. You can initialize an awk variable to a string that includes the value of a bash variable using -v but awk isn't accessing the bash variable, bash is accessing the bash variable to populate the -v... part before it calls awk. There is no way for bash to have access to awk variables - if you want to set some bash variables based on values of awk variables then you need to print the values of those awk variables from awk and read those values in bash, eg to read all awk output values into a bash array:

$ awk 'BEGIN{foo=7; bar="stuff"; print foo; print bar}'
7
stuff

$ out=( $(awk 'BEGIN{foo=7; bar="stuff"; print foo; print bar}') )

$ echo "${out[0]}"
7
$ echo "${out[1]}"
stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM