Well done! You learn quickly.
You don't need two separate loops, however. You can process both variables in one pass. Your
printf function was using the wrong syntax too.
I've also looked a bit at ps, and you can indeed tell it to output only the fields you want.
First the awk script, which I set to be stand-alone. It's mostly just a modified version of what you posted .
Code:
#!/usr/bin/awk -f
{
if ( $0 ~ /Dxxx.home/ ) {
# Loop over all arguments (NF is the argument-count)
for ( i=0 ; i<=NF ; i++ ) {
# If the argument is either -c or -p save the position of the next argument into a variable
if ( $i == "-c" ) { config_arg = i+1 }
if ( $i == "-p" ) { process_arg = i+1 }
}
# Do the output. Precede vars with $ to get the arguments and not just their position...
printf "\tConf: %s\tProcess: %s\tPID: %s\n" , $config_arg , $process_arg , $1
}
}
And to run it:
Code:
ps -eo "pid cmd" | script.awk
(
ps also has a
-C option, which matches the name of a process. But I don't know if it would work in this case as the process name appears to be variable. )
In fact, if you want, you can use
getline to incorporate the command input straight into the awk script itself, and just run it stand-alone.
Code:
#!/usr/bin/awk -f
BEGIN{
while ( ( "ps -eo 'pid cmd'" ) | getline ) {
if ( $0 ~ /Dxxx.home/ ) {
# Loop over all arguments (NF is the argument-count)
for ( i=0 ; i<=NF ; i++ ) {
# If the argument is either -c or -p save the position of the next argument into a variable
if ( $i == "-c" ) { config_arg = i+1 }
if ( $i == "-p" ) { process_arg = i+1 }
}
# Do the output. Precede vars with $ to get the arguments and not just their position...
printf "\tConf: %s\tProcess: %s\tPID: %s\n" , $config_arg , $process_arg , $1
}
}
}