help-gnu-utils
[Top][All Lists]
Advanced

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

awk - Read file inside script.


From: Chris Jones
Subject: awk - Read file inside script.
Date: Sun, 04 Jan 2009 22:27:59 -0500
User-agent: Mutt/1.5.13 (2006-08-11)

I'm tidying up some awk one-liners and I rewrote one as a short awk
script that does what I need when run thus:

$ script /proc/meminfo

I would like to specify the file inside the script in order to be able
to run it thus:

$ script

Here's the script:


#!/usr/bin/gawk -f
#-------------------------------------------------------------------------------
# ./memswap :   display percentage of ram & swap currently in use
#
# usage     :   GNU/screen backtick
#
# notes     :   % ram used  = ((total ram  - used ram)  / total ram)  * 100
#           :   % swap used = ((total swap - used swap) / total swap) * 100   
#-------------------------------------------------------------------------------
{
        if ($1=="MemTotal:")    {mt = $2}       # mt = total ram on system 
        if ($1=="MemFree:")     {mf = $2}       # mf = free ram
        if ($1=="Buffers:")     {mb = $2}       # mb = ram used for buffers 
        if ($1=="Cached:")      {mc = $2}       # mc = ram used for cache 
        if ($1=="SwapTotal:")   {st = $2}       # st = total swap
        if ($1=="SwapFree:")    {sf = $2}       # sf = free swap  
}                                                   
END {
    pmu=((mt-(mf+mb+mc)) * 100 / mt)            # pmu = % of ram  used
    psu=((st-sf) * 100 / st)                    # psu = % of swap used
    printf ("%2.1f %s %2.1f %s\n"), pmu, "%", psu, "%"
}

In pseudo-code this is as simple as:

while read next-record                          # till EOF
   extract data
end

compute + print percentages

exit

It is meant to be invoked from GNU/screen at fixed intervals of time via
the "backtick" mechanism so that I don't have to worry about closing the
file or sleeping for some length of time & reiterating the process. 

I have tried numerous things with while .. getfile .. restructuring the
above, adding a BEGIN section .. and gotten nowhere.

Hope this makes sense.

Thanks!

CJ




reply via email to

[Prev in Thread] Current Thread [Next in Thread]