Home > Mobile >  Regex to match PID with grep?
Regex to match PID with grep?

Time:07-06

I want to match 6202/java or 6202

tcp6       0      0 127.0.0.1:2014          :::*                    LISTEN      6202/java

With regex web tooling I am able to match it but if I use "\S*$" regex to match non white space up to the end of the string I get nothing.

sudo netstat -tulpn | grep java | grep -o "\S*$"

CodePudding user response:

Using sed

$ sudo netstat -tulpn | sed -n '/java/s/.* //p'

CodePudding user response:

You might be interested in a somewhat different alternative. The command lsof allows you to query based on program name.

$ lsof -Pan -i -c java

This outputs some tabulated data. If you add -F string to it, you can ask it what to output in a way that is easily processable with tools such as awk and sed. The default will just output the pid and file descriptors, so you can do something like:

$ lsof -Pan -i -F'' -c java | awk '/^p/{print substr($0,2)}'

Details of lsof can be found in man lsof

CodePudding user response:

You can write the grep command as:

sudo netstat -tulpn | grep -o "[^[:space:]]\ java[[:space:]]*$"

Using -o

Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

The pattern matches:

  • [^[:space:]]\ Match 1 non whitespace chars
  • java Match literally
  • [[:space:]]* Match optional spaces
  • $ End of string

Output

6202/java

If you want to have the digits only and -P is supported for a perl compatible regex you can match 1 digits and assert /java to the right at the end of the string:

sudo netstat -tulpn | grep -oP "\d (?=/java\s*$)"

Output

6202

CodePudding user response:

With your shown samples and attempts, please try following codes.

1st solution: Running netstat command with tulpn options and sending its output to awk code. In awk code making field separators as either space OR / and then checking if last field is java then print last 2 fields of that line.

sudo netstat -tulpn | 
awk -F' |/' '
 $NF=="java"{
  print $(NF-1),$NF
 }
'


2nd solution: Running netstat command with tulpn options and sending its output to awk code. In awk code using split function to split last field with separator as / and creating an array named arr AND checking further condition if 2nd element of that array is java then print both of the elements of that array(which will be last and 2nd last field of that line).

sudo netstat -tulpn | 
awk '
split($NF,arr,"/")==2 && arr[2]=="java"'{
  print arr[1],arr[2]
}'


3rd solution: Using GNU grep try following code. Using its -oP options to print exact matched value and enabling PCRE regex respectively. In main program matching value till last space occurs followed by a \K to forget that matched regex and matching digits(1 or more occurrences) and making sure its followed by /java using positive look ahead mechanism.

sudo netstat -tulpn | grep -oP '.*[[:space:]] \K\d (?=/java)'
  • Related