2

I'm trying to make a custom polybar module that shows the current active window class, since the default module outputs the window name.

I'm using this command to get the window class:

xprop -id $(xdotool getactivewindow) WM_CLASS

and getting this output:

WM_CLASS(STRING) = "kitty", "kitty"

but the desired output is:

kitty

how can i do that?

1
  • 1
    Which one of the kitties, the first or the second? No, the "instance" and "class" are not always identical. Also, many windows don't have any WM_CLASS at all.
    – user313992
    Apr 5, 2020 at 5:22

3 Answers 3

2

You may get away with:

xprop -id $(xdotool getactivewindow) WM_CLASS | 
    awk -F '"' '{print $2}'

But also with (the simpler):

xprop -id $(xdotool getactivewindow) WM_CLASS | 
    cut -d '"' -f 2

Or (warning, if the regex fails to match, the whole input will be printed)

xprop -id $(xdotool getactivewindow) WM_CLASS | 
    sed 's/^[^"]*"\([^"]*\)".*$/\1/'

Or, sed again, but a bit more robust:

xprop -id $(xdotool getactivewindow) WM_CLASS |
    sed -n 's/^[^"]*r"\([^"]*\)".*$/\1/p'

Or, even (not so robust) with grep (but only GNU grep and with Perl regex):

xprop -id $(xdotool getactivewindow) WM_CLASS |
    grep -Po  '^[^"]*"\K[^"]*'

Is that what you mean?
In words: extract the string inside the first pair of quotes, fail otherwise ?

1

xprop outputs strings in a very similar format to that of ksh93/zsh/bash's $'...' quoting where backslash, control and non-ASCII characters are represented as their ANSI C \\, \n, \r, \t or \ooo notation.

The only difference is that because they're enclosed in double quotes, " itself is rendered as \" and ' rendered as ' instead of \', so it should not be too difficult to convert that output to WM_CLASS=$'...' to be evaluated by the shell.

However it's even easier (and safer) to get xprop to output it as hex values, and transform to $'\xHH...':

For the application name (the first kitty in your example):

eval "$(
  xprop -id "$(xdotool getactivewindow)" -notype 8x WM_CLASS |
    sed 's/0x/\\x/g;s/[, ]//g;s/\\x0.*/'\''/;s/=/=$'\'/
)"

for the application class name (the second kitty in your example):

eval "$(
  xprop -id "$(xdotool getactivewindow)" -notype 8x WM_CLASS |
    sed 's/0x/\\x/g;s/[, ]//g;s/=.*\\x0\(.*\)\\x0/=$'"'\\1'/"
)"

Both set the $WM_CLASS shell variable.

That would work regardless of what byte value the property may contain.

Assumes a shell with support for $'\xHH'.

0

Tried with method

xprop -id $(xdotool getactivewindow) WM_CLASS| awk '{gsub(/[","]/,"",$3);print $3}'


output

kitty

python

output of command "xprop -id $(xdotool getactivewindow) WM_CLASS" is saved in variable "a"

#!/usr/bin/python
import re
a='"WM_CLASS(STRING) = "kitty", "kitty"'
b=a.split(' ')[2]
print b.replace('"','').replace(",","")

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .