Teerawat
Teerawat

Reputation: 13

How to grep first match and second match(ignore first match) with awk or sed or grep?

> root# ps -ef | grep [j]ava |  awk '{print $2,$9}'                                                             
> 45134 -Dapex=APEC
> 45135 -Dapex=JAAA
> 45136 -Dapex=APEC

I need to put the first APEC of first as First PID, third line of APEC and Second PID and last one as Third PID.

I've tried awk but no expected result.

> First_PID =ps -ef | grep [j]ava |  awk '{print $2,$9}'|awk '{if ($0 == "[^0-9]" || $1 == "APEC:") {print $0; exit;}}'

Expected result should look like this.

> First_PID=45134
> Second_PID=45136
> Third_PID=45135

Upvotes: 1

Views: 235

Answers (4)

Teerawat
Teerawat

Reputation: 13

After read from everyone idea,I end up with the very simple solution.

FIRST_PID=$(ps -ef | grep APEC | grep -v grep | awk '{print $2}'| sed -n '1p') 
SECOND_PID=$(ps -ef | grep APEC | grep -v grep | awk '{print $2}'| sed -n '2p') 
JAWS_PID=$(ps -ef | grep JAAA | grep -v grep | awk '{print $2}')

Upvotes: 0

Paul Hodges
Paul Hodges

Reputation: 15293

If you just want the APECs first...

ps -ef |
  awk '/java[ ].* -Dapex=APEC/{print $2" "$9; next; }
       /java[ ]/{non[NR]=$2" "$9}
       END{ for (rec in non) print non[rec] }'

If possible, use an array instead of those ordinally named vars.

mapfile -t pids < <( ps -ef | awk '/java[ ].* -Dapex=APEC/{print $2; next; }
 /java[ ]/{non[NR]=$2} END{ for (rec in non) print non[rec] }' )

Upvotes: 0

Bach Lien
Bach Lien

Reputation: 1060

How about this:

$ input=("1 APEC" "2 JAAA" "3 APEC")
$ printf '%s\n' "${input[@]}" | grep APEC | sed -n '2p'
3 APEC

Explanation:

  • input=(...) - input data in an array, for testing
  • printf '%s\n' "${input[@]}" - print input array, one element per line
  • grep APEC - keep lines containing APEC only
  • sed -n - run sed without automatic print
  • sed -n '2p' - print only the second line

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133518

With your shown samples and attempts please try following awk code. Written and tested in GNU awk.

ps -ef | grep [j]ava | 
awk '
{
  val=$2 OFS $9
  match(val,/([0-9]+) -Dapex=APEC ([0-9]+) -Dapex=JAAA\s([0-9]+)/,arr)
  print "First_PID="arr[1],"Second_PID=",arr[3],"Third_PID=",arr[2]
}
'

Upvotes: 2

Related Questions