Monday, October 24, 2022

[SOLVED] How can I remove the characters or text to show only the PID in terminal. Ubuntu/Linux terminal

Issue

How can I remove the characters/texts from this output? I've been trying to sed/cut but I cant really do it.

My command:

xprop -id $(xprop -root 32x '\t$0' _NET_ACTIVE_WINDOW | cut -f 2) _NET_WM_PID

Output:

_NET_WM_PID(CARDINAL) = 3239

Expected output:

3239

Solution

You can do this using cut alone. Note that the cut command has the argument -d which defaults to tab but you can pass other delimiter.

xprop -id $(xprop -root _NET_ACTIVE_WINDOW | cut -d\# -f2) _NET_WM_PID | cut -d\  -f3

Lets break this down into its parts, and start at the inside.

  • xprop -root _NET_ACTIVE_WINDOW | cut -d\# -f2 select the id, by using the pound symbol as delimiter for cut, the first field is everything before the # and the second field is everything behind the first #, here it is the id
  • $( ... ) is replaced by the result of the command inside the parens, here that is the id
  • xprop -id $( ... ) _NET_WM_PID | cut -d\ -f3 the outer xprop result can be cutted at the space, which give use three fields:
    • _NET_WM_PID(CARDINAL)
    • =
    • the value (without leading space as one would get by using = as delimiter)
  • Note that we use -d\ to specify "space as delimiter", we need to escape the space with a backslash.


Answered By - Lars Fischer
Answer Checked By - Mary Flores (WPSolving Volunteer)