I want to grep for a word in a file in the last n lines without using the pipe.
grep <string> filename
enables to search the filename for a string. But, I want to search for a string in the last N lines of the file. Any command to search for that without using the pipe?
Best Answer
If your shell supports it (
zsh
,bash
, some implementations ofksh
), you could utilise process substitutionWhere -n5 means get the five last lines.
Similarly,
would search through the 5 first lines of yourfile.txt.
Explanation
Simply speaking, the substituted process pretends to be a file, which is what grep is expecting. One advantage with process substitution is that you can feed output from multiple commands as input for other commands, like
diff
in this example.1Note that with
ksh93
on Linux at least,|
does not use a pipe but a socket pair while process substitution does use a pipe (as it's not possible toopen
a socket):