Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing ps and grep output in shell

I get the following message when I do a "ps -ef | grep port"

apache    6215     1  0 11:20 ?        00:00:00 perl /scripts/myscript.pl -sn 4123E -sku HSME01-HW -port 8

Is there a way to parse the following:

  • start time (11:20)
  • sn (4123E)
  • sku (HSME01-HW)
  • port (8)
like image 715
Jeremy Avatar asked Aug 06 '13 18:08

Jeremy


People also ask

How do you grep the output of a command in shell script?

Using Grep to Filter the Output of a CommandA command's output can be filtered with grep through piping, and only the lines matching a given pattern will be printed on the terminal. You can also chain multiple pipes in on command. As you can see in the output above there is also a line containing the grep process.

What is* in grep?

* has a special meaning both as a shell globbing character ("wildcard") and as a regular expression metacharacter. You must take both into account, though if you quote your regular expression then you can prevent the shell from treating it specially and ensure that it passes it unchanged to grep .


1 Answers

You can use awk for both filtering and parsing:

ps -ef | awk '/[p]ort/ {printf "start time: %s\nsn: %s\nsku: %s\nport: %s\n", $5, $11, $13, $NF}'

As glenn jackman pointed out in the comments the square brackets in the filter string prevent the expression from matching the filter string itself in the process list.

like image 110
Ansgar Wiechers Avatar answered Nov 15 '22 06:11

Ansgar Wiechers