4

I need to set my keyboard layout with setxkbmap before launching Wine games, as I use Dvorak for typing and this breaks every game's controls. What I'd like to do is simply write a script that grabs the current keyboard layout before starting the game, stores it in a variable, then restores it after the game is done:

ORIGINAL_LAYOUT=`setxkbmap -query | grep -P 'layout\:\s{5}(\w+)'`
setxkbmap us
wine ...
setxkbmap $ORIGINAL_LAYOUT

The problem that I'm having is that grep matches the entire line and not just my capture group. Is there a way for me to simply dump the matched capture group?

For example, the output of setxkbmap -query is:

rules:      evdev
model:      pc105
layout:     dvorak

I'm interested in grabbing the layout.

Naftuli Kay
  • 39,676

2 Answers2

6

You can use -o and change the grep a little bit

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

.

ORIGINAL_LAYOUT=`setxkbmap -query | grep -oP '(?<=layout\:\s{5})\w+'`

We changed the regex to use a look-behind so its not part of the match

phemmer
  • 71,831
5

Try using this awk command:

setxkbmap -query | grep layout | awk '{print $2}'

or use cut command

setxkbmap -query | grep layout | cut -d : -f2