Question

I have a bash script for hiding X11 windows. I want to be able to find what window the mouse is positioned over and unmap that window.

Using xdotool I've gotten a way to find the window ID:

$ xdotool getmouselocation
x:392 y:344 screen:0 window:54799020

I want to trim this line to just 54799020.
(I want to remove everything up to and including window:.)

Is there a way to do this? I have very little experience with tr and sed. I've used sed to remove text before, but I need to also remove the mouse coordinates, which are not always the same.

Was it helpful?

Solution 3

Try this,

sed 's/.*window:\(.*\)/\1/g' file  

In your case,

xdotool getmouselocation | sed 's/.*window:\(.*\)/\1/g'

Example:

$ echo "x:392 y:344 screen:0 window:54799020" | sed 's/.*window:\(.*\)/\1/g'
54799020

OTHER TIPS

awk with field seperator : and grab column 4

You can use an awk script like this

#!/bin/awk
BEGIN { FS=":";}
print $5

or run it on the command line.

awk -F':' '{print $5}' file

and in your case

xdotool getmouselocation | awk -F':' '{print $5}' -

set it to a variable (which is probably what you are doing)

WINDOWLOC=`xdotool getmouselocation | awk -F':' '{print $5}' -`

or

WINDOWLOC=$(xdotool getmouselocation | awk -F':' '{print $5}' -)

For the general case in your question title, this can be done in bash alone in at least two ways.

One uses bash string manipulation:

# ${VARIABLE##pattern} trims the longest match from the start of the variable.
# This assumes that "window:nnnnnn" is the last property returned.

DOTOOL_OUTPUT=$(xdotool getmouselocation)
WINDOW_HANDLE=${DOTOOL_OUTPUT##*window:}

As a mnemonic, # is to the left of $ on the keyboard and trims the start of the string; % is to the right of $ and trims the end of the string. # and % trim the shortest pattern match; ## and %% trim the longest.

The other way uses bash regular expression matching:

# Within bash's [[ ]] construct, which is a built-in replacement for
# test and [ ], you can use =~ to match regular expressions. Their
# matching groups will be listed in the BASH_REMATCH array.

# Accessing arrays in bash requires braces (i.e. ${ } syntax).

DOTOOL_OUTPUT=$(xdotool getmouselocation)
if [[ $XDOTOOL_OUTPUT =~ window:([0-9]+) ]]; then
  WINDOW_HANDLE=${BASH_REMATCH[1]}
fi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top