Bash脚本:删除字符串中的字符,包括短语?

时间:2014-05-04 15:38:07

标签: bash shell sh xdotool

我有一个用于隐藏X11窗口的bash脚本。我希望能够找到鼠标所在的窗口并取消映射该窗口。

使用xdotool我找到了查找窗口ID的方法:

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

我想将此行修剪为54799020。(我希望删除所有内容,包括window:。)

有办法做到这一点吗?我对trsed的经验很少。我之前使用sed删除了文字,但我还需要删除鼠标坐标,这些坐标并不总是相同。

3 个答案:

答案 0 :(得分:2)

awk with field seperator :并抓住第4列

您可以使用像这样的awk脚本

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

或在命令行上运行它。

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

,在你的情况下

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

将其设置为变量(可能就是你正在做的事情)

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

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

答案 1 :(得分:2)

对于问题标题中的一般情况,这可以通过至少两种方式单独使用bash来完成。

一个使用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:}

作为助记符,#位于键盘上$的左侧,并修剪字符串的开头; %位于$的右侧,并修剪字符串的结尾。 #%修剪最短的模式匹配; ##%%修长时间最长。

另一种方式使用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

答案 2 :(得分:1)

试试这个,

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

在你的情况下,

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

示例:

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