Reputation: 11
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?
Upvotes: 1
Views: 178
Reputation: 133468
With your shown samples please try following awk
code. We need NOT to traverse through all fields, since its output of ps
command so values will be searched in 9th and 10th fields, please try following.
pat1="/opt1/scripts/"
awk -v pattern="$pat1" 'index($9,pattern) || index($10,pattern){print $2,$9}' Input_file
Upvotes: 3
Reputation: 11217
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
Upvotes: 1
Reputation: 163287
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
Upvotes: 3