Here is the description of grep from GNU.org:
grepsearches 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?
2 Answers
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
grepsearches 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,grepsearches he working directory.if given a command-line option specifying recursion; otherwise,grepsearches 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}' 1 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/stdinYou can get the desired output with grep alone (no awk needed):
% xrandr | grep -Po '^[^ ]+(?= connected)'
LVDS1This 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).