2

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.

5

Try using this awk command:

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

or use cut command

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

  • 2
    The grep is unnecessary, see jasonwryan's comment to the question. – Mat Jan 2 '12 at 18:58
4

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

  • This would have returned the full line, not the part between parentheses. – Lekensteyn Jan 2 '12 at 21:40
  • @Lekensteyn This is why you modify the regex to use look-behind... – Patrick Jan 3 '12 at 12:46
  • Include that in your answer then. Nifty trick btw, it never occured to me to use lookbehind in grep. – Lekensteyn Jan 3 '12 at 13:43
  • @Lekensteyn advice taken – Patrick Jan 3 '12 at 19:53
  • 2
    Note: -P is not supported since OSX Lion and on BSD grep – kenorb Sep 24 '13 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.