Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ...

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.

share|improve this question
You mean like awk '/layout/ {print $2}'? – jasonwryan Jan 2 '12 at 18:50
See this answer: unix.stackexchange.com/questions/24722/… – camh Jan 2 '12 at 22:24
possible duplicate of Can grep output only specified groupings that match? – Gilles Jan 2 '12 at 23:40
up vote 5 down vote accepted

Try using this awk command:

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

or use cut command

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

share|improve this answer
The grep is unnecessary, see jasonwryan's comment to the question. – Mat Jan 2 '12 at 18:58

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

share|improve this answer
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
Note: -P is not supported since OSX Lion and on BSD grep – kenorb Sep 24 '13 at 9:57

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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