Tel*_*Why 5 xrandr command-line grep find
以下是grep来自GNU.org的描述:
grep在输入文件中搜索包含与给定模式列表匹配的行。当它在一行中找到匹配项时,它会将该行复制到标准输出(默认情况下),或者生成您使用选项请求的任何其他类型的输出。
我有一个我经常使用的命令,它给出了当前连接的监视器的名称:
xrandr | grep " connected " | awk '{ print$1 }'
Run Code Online (Sandbox Code Playgroud)
我在此命令中看不到任何文件或指向它们的链接,那么到底发生了什么?被grep用于其他的东西,除了搜索文件?
mur*_*uru 14
来自man grep(强调我的):
grep searches the named input FILEs (or standard input if no files are
named, or if a single hyphen-minus (-) is given as file name) for lines
containing a match to the given PATTERN. By default, grep prints the
matching lines.
Run Code Online (Sandbox Code Playgroud)
来自GNU 文档(再次强调我的):
2.4 grep 程序
grep在命名输入文件中搜索包含与给定模式匹配的行。默认情况下,grep 打印匹配的行。一个名为的文件-代表标准输入。如果未指定 input, 则在给定指定递归的命令行选项的情况下grep搜索工作目录.;否则,grep搜索标准输入。
在这种情况下,标准输入是连接到xrandr标准输出的管道。
的grep是在这种情况下多余; awk可以自己完成这项工作:
xrandr | awk '/ connected /{print $1}'
Run Code Online (Sandbox Code Playgroud)
hee*_*ayl 10
当你这样做时:
xrandr | grep " connected "
Run Code Online (Sandbox Code Playgroud)
您基本上是将 的标准输出(文件描述符 1, /dev/stdout)重定向xrandr到 的标准输入(文件描述符 0, /dev/stdin)grep,这是管道的工作。
由于grep当没有给出文件名,从标准输入获取输入,您的命令将尽可能的文件而言成功。
你可以把它想象成:
grep 'pattern' /dev/stdin
Run Code Online (Sandbox Code Playgroud)
您可以grep单独获得所需的输出(awk不需要):
% xrandr | grep -Po '^[^ ]+(?= connected)'
LVDS1
Run Code Online (Sandbox Code Playgroud)
这将获得行 ( ^[^ ]+)的第一个空格分隔的单词,后跟一个空格,然后是单词connected((?= connected)是一个零宽度正前瞻模式,确保<space>connected在所需部分之后匹配)。