Playing with awk


Results 1 to 5 of 5

Thread: Playing with awk

Threaded View

  1. #1
    Join Date
    Jul 2002
    Location
    New Orleans, LA USA
    Posts
    986

    Playing with awk

    Most of the things I need to do now-a-days I have scripted and saved away for when I need them, or even on a cron schedule (read: I've become lazy with BASH scripting). So I started trying to solve some basic problems from scratch using filters and pipes to refresh myself. As an added bonus, I allowed myself only one line - so everything has to be pipped are otherwise segmented. At any rate, I managed to back myself into a corner without too much effort. I don't really need this function, but it is the fact that I can't readily make it happen that urks me...

    I started simple with stuff like let's see a unique list of everyone logged into this server. Fine, easy, done.

    Code:
    who | awk '{print $1}' | uniq
    Then I said ok, let's see what processes these users have open. Easy enough, mostly swap w for who.

    Code:
     w | awk '{print $1 " - " $8}' | uniq
    Moving on, I said to myself w doesn't catch things that are still running from a closed session (nohup, process &, etc.), so I'll use ps and /etc/passwd (Debian starts user accounts at PID 1000). Took me a little longer to build, but wasn't overly difficult.

    Code:
    awk -F: '{print $1,$3}' /etc/passwd | while read user pid; do (( pid >= 1000 )) && ps aux | grep $pid | awk '{print $1 " - " $11}' | uniq; done
    So far so good, except then I decided I want a summary style output instead of just every process for every user printed (for example, unique list of users with total number of processes next to each user name). That is when I hit a wall, because I now need to run two loops and store the result of the first while running the second - and I don't know how to accomplish that in one line.

    By picking a single user and not needing their id displayed, the code becomes trivial with something like:

    Code:
    ps -u 1000 | wc -l | awk '{print $1-4}'
    However, what if I want ps to cycle through all the users in /etc/passwd and return the user id and the total open processes for that id - to look like:

    Code:
    user1  20
    user2  15
    user3  11
    ...
    Any ideas? Only real restrictions I've placed on myself are stay in BASH and execute off one line.
    Last edited by trilarian; 08-27-2010 at 04:33 PM. Reason: grammar
    "Whenever you find yourself on the side of the majority, it's time to pause and reflect."

    -Mark Twain

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •