Trying to join output from ps and pwdx linux comma

2019-09-16 14:23发布

问题:

I am trying to join output from ps and pwdx command. Can anyone point out the mistake in my command.

ps -eo %p,%c,%u,%a --no-headers | awk -F',' '{ for(i=1;i<=NF;i++) {printf $i", 
"} ; printf pwdx $1; printf "\n" }'

I expect the last column in each row to be the process directory. But it just shows the value of $1 instead of the command output pwdx $1

This is my output sample (1 row):

163957, processA , userA , /bin/processA -args, 163957

I expected

163957, processA , userA , /bin/processA -args, /app/processA

Can anyone point out what I may be missing

回答1:

Try this:

ps -eo %p,%c,%u,%a --no-headers | awk -F',' '{ printf "%s,", $0; "pwdx " $1 | getline; print gensub("^[0-9]*: *","","1",$0);}'

Explanation:

awk '{print pwdx $1}' will concatenate the awk variable pwdx (which is empty) and $1 (pid). So, effectively, you were getting only the pid at the output.

In order to run a command and gets its output, you need to use this awk construct:

awk '{"some command" | getline; do_something_with $0}'
# After getline, the output will be present in $0.

#For multiline output, use this:
awk '{while ("some command" | getline){do_something_with $0}}'
# Each individual line will be present in subsequent run of the while loop.


回答2:

Simplifying your example to focus on how to execute the pwdx command within awk and capture the result of this command into an awk variable as this is where you were having issues:

ps -eo %p,%c,%u,%a --no-headers | awk -F',' '{ system("pwdx "$1) | getline vpwdx; printf vpwdx $1}'

produces:

  15651665: /
  16651690: /
  16901691: /home/fpm
 169134248: /home/fpm
3424834254: /home/fpm/tmp
3425440181: /home/fpm/UDK2015
...