grep and printf

WeeZer51402

Registered
is there anyway to format output from grep with printf, and is there a way for me to only get certain elements from a line?
 
Yes, and that way is awk. Read the manpage for it, and see where that gets you. It's a bit of a beast, though, kind of a 274-in-1 tool, and you only need about 3 of its features.

Or, depending on how complex your needs are, you could just write a little program in C or perl or your language of choice
 
Are you sure you want to use printf(1)? What is the task?
Anyways, "sed" might be what you are looking for. I find it easier to use than awk.
Better don't get started with the man page though. Look for an example-driven tutorial or similar, it might take you further in less time.
 
I use awk with grep often, and it works no problem.

The files I use grep and awk on are internet log access files. They all have a standard format. In any given line you have 9 element (or columns) separated by spaces. So, what I do when I want to grep for a particular piece of data and only use part of the return grep lines is something like this....


grep "someData" someLogfile.txt | awk '{print $3 }'

This will return only the third element/column of all the lines that contain "someData".

In other words....

aaa bbb ccc ddd eee someData fff ggg hhh
aba bab cbc dnd ena xxx kkk lll mmm
xxx aaa mmm zzz kak ttt sss yyy ggg
kkk someData fff ttt 111 iii ddd hah yiy

...would be returned as...

ccc
fff

Hope this bit of info helps.

m(_ . _)m
 
what I'm trying to do is 'ps acxu | grep AppleFileServer' but all i want to do is just get user, PID and command not cpu usage and all that other stuff, basically just to monitor who is connected to my machine. the kind of outpu im loong for is something like this-

USER PID COMMAND
user 927 AppleFileServer
 
This Works:

ps acxu | grep PID | awk '{print $1, $2, $11}' ; ps axcu | grep AppleFileServer | awk '{print $1, $2, $11}';

But the Problem is that root owns all the processes.
 
You may want to add x to that - the above'll only list some of the processes running, not all of them.

Here, do this one: ps -axcouser,pid,command

Here's how I have my ps set up: ps -axouser,pid,tt,nice,stat,xstat,nswap,start,command. That gives me: user, pid, controlling TTY, nice value it's running as, processes' stat, exit or stop status (valid only for stopped or zombie procs), total swaps in/out (always zero for me though, may not be actually working...but I have a gig of ram...dunno), time the process started, and the command name plus it's path and any command line arguments given to it (will only display like 128 characters, though, so some stuff will get chopped off). If you want your command like that, drop the c from the arguments to ps. ;)
 
Back
Top