What does grep do?
Solution 1
From man grep
(emphasis mine):
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.
And from the GNU docs (again, emphasis mine):
2.4 grep Programs
grep
searches the named input files for lines containing a match to the given pattern. By default, grep prints the matching lines. A file named-
stands for standard input. If no input is specified,grep
searches he working directory.
if given a command-line option specifying recursion; otherwise,grep
searches standard input.
The standard input, in this case, is the pipe connected to xrandr
's standard output.
The grep
is superfluous in this case; awk
can do the job by itself:
xrandr | awk '/ connected /{print $1}'
Solution 2
When you do:
xrandr | grep " connected "
you are basically redirecting the standard output (file descriptor 1, /dev/stdout
) of xrandr
to the standard input (file descriptor 0, /dev/stdin
) of grep
, this is the job of the pipe.
As grep
takes input from standard input when no file name is given, your command will succeed as far as the file is concerned.
You can think of it as:
grep 'pattern' /dev/stdin
You can get the desired output with grep
alone (no awk
needed):
% xrandr | grep -Po '^[^ ]+(?= connected)'
LVDS1
This will get the first space separated word of the line (^[^ ]+
) followed by a space and then the word connected
((?= connected)
is a zero width positive lookahead pattern ensuring <space>connected
is matched after the desired portion).
Related videos on Youtube
Comments
-
TellMeWhy over 1 year
Here is the description of
grep
from GNU.org:grep
searches input files for lines containing a match to a given pattern list. When it finds a match in a line, it copies the line to standard output (by default), or produces whatever other sort of output you have requested with options.I have this command that I use often, which gives the name of the currently connected monitor:
xrandr | grep " connected " | awk '{ print$1 }'
I can't see any files in this command, or links to them, so what exactly is going on? Is
grep
used for other stuff apart from searching files? -
TREE over 8 yearsIt should be noted that this mechanism of creating strings of small commands that can work on input via pipes is a key part of the unix philosophy, and extremely common in unix and linux.