i want to get the related pids which match certain pattern, and then show the results with the pids and the matching part of the commands
samples results from ps (note that the target column is not necessary $9. eg $9 in line 1 and $10 in line 2):
root 23775 1 0 18:40 ? 00:00:01 /bin/bash /opt1/scripts/datamon/check_usage.sh -t 10
root 23777 1 0 18:40 ? 00:00:01 /bin/bash /opt1/servers/rt/extract_data.sh /opt1/scripts/datamon/results.data
what i am doing is:
pat1="/opt1/scripts/"
ps -ef | grep 'datamon' | awk -v RS='\n' -v pattern="$pat1" '{for (i=1;i<=NF;i ){if($i == /^pattern/) {print $2" "$i}}}'
the results obtained via the above commands are (pids are correct but not the command):
23775 0
23777 0
but actually what i want is:
23775 /opt1/scripts/datamon/check_usage.sh
23777 /opt1/scripts/datamon/print_results.sh
question:
1 why i got "0" instead of the matching commands?
2 how can i print the correct results above?
regards
CodePudding user response:
In the second part you are doing a string compare ==
instead of using ~
for a regex match.
If you print /^pattern/
it will give 0.
So if($i == /^pattern/)
becomes if(0 == 0)
and is true for field 4, which has 0 in the data and is printed.
You can print field 9 instead of $i
as that field contains the data that you are interested in.
pat1="/opt1/scripts/"
awk -v pattern="$pat1" '
{
for (i=1;i<=NF;i ){
if($i ~ pattern) {
print $2" "$9
}
}
}' file
Output
23775 /opt1/scripts/datamon/check_usage.sh
23777 /opt1/servers/rt/extract_data.sh
You can also print the field where the match is with print $2" "$i
but then the output will be:
23775 /opt1/scripts/datamon/check_usage.sh
23777 /opt1/scripts/datamon/results.data
CodePudding user response:
Using GNU sed
$ pat1="/opt1/scripts/"
$ ps -ef | sed -En "/datamon/{s~[^ ]* ([^ ]* ).*($pat1[^ ]*).*?~\1\2~p}"
23775 /opt1/scripts/datamon/check_usage.sh
23777 /opt1/scripts/datamon/results.data