How to extract a key value pair from ps command
You're not showing the error message you are getting but it's probably
grep: unknown devices method
That's because, like all or at least most other command line programs, grep
assumes that anything that starts with a -
is an option and tries to parse it as such. In this case, -D
is used to instruct grep
on how to deal with a device file (see man grep
for details). One way to get around this is to use --
which tells grep
that anything following is not an option flag.
Combining that with the PCRE capability of GNU grep
, you can do:
ps -af -u sas | grep -v grep | grep -Po -- '*-\KDapp.name=[^\s]+'
The regular expression searches for a -
and discards it (\K
), then the string Dapp.name=
followed by as many non-space characters as possible. The output is:
Dapp.name=myApp
If you want the myApp
part saved in a variable, I would search for that alone:
ps -af -u sas | grep -v grep | grep -Po -- '-Dapp.name=\K[^\s]+'
To assign it to a variable:
$ app="$(ps -af -u sas | grep -v grep | grep -Po -- '-Dapp.name=\K[^\s]+')"
$ echo $app
myApp
However, you should never grep
the output of ps
for this kind of thing, that's what pgrep
is for:
app="$(pgrep -a java | grep -Po -- '^Dapp.name=\K[^\s]+')"
With awk
:
ps -af -u sas | awk 'BEGIN {RS=" "}; /-Dapp.name/'
ps -af -u sas | sed -n '/[j]ava/s/.*-Dapp\.name=\([^ ]*\).*/\1/p'