2

When using: "ps -fu ${USER} | grep address" I can find the java process and also, the debug port number which appears as part of the process command line. My question, is how do I extract the port number from the command line which contains many characters. The question can be summed up to how can I extract a word between 2 strings. I have been looking up how to do it with grep, awk or sed. But all my trial ended with displaying the entire process command line and not just the java port number.

Thanks ahead.

user3108139
  • 33
  • 1
  • 3
  • It would have been most helpful if you would have added a sample of such a command line. I can only assume it's something like `java -Xdebug -Xrunjdwp:transport=dt_socket,address=8998,server=y -jar myapp.jar` but of course I'm just guessing as it stands. – fvu Dec 16 '13 at 17:06
  • 1
    possible duplicate of [How to extract text between two words in unix?](http://stackoverflow.com/questions/6127786/how-to-extract-text-between-two-words-in-unix) – Jacek Laskowski Dec 16 '13 at 17:26
  • Please always do a search first before posting a new question, and also, please try to ask the real question (in your case, how to extract word between two strings) rather than starting out with the context. If you remove the context, you will also notice quickly that the question has already been asked. – Christian Fritz Dec 16 '13 at 17:28

1 Answers1

2

You can extract the debug port with sed:

ps -fu ${USER} | grep address | sed 's/.*address=\([0-9]*\).*/\1/'

Update:

The output from ps may include the grep command itself. You can use grep again to filter that out:

ps -fu ${USER} | grep address | sed 's/.*address=\([0-9]*\).*/\1/' | grep ^\d
joemfb
  • 3,056
  • 20
  • 19
  • Thank a lot! Eventually I used following to get just the port number: ps -fu ${USER} | grep address | sed 's/.*address=\([0-9]*\).*/\1/' | head -n 1. Actually, now I noticed that for some servers I can see the debug port after and for some before the line which prints the "grep address". strange... – user3108139 Dec 18 '13 at 12:55
  • And finally this is the command I have found perfectly working: ps -fu ${USER} | grep address | sed 's/.*address=\([0-9]*\).*/\1/' | grep -v ${USER} | grep -v "^[[:blank:]]*$" Thanks again for the excellent answer – user3108139 Dec 18 '13 at 13:11