Grep for a string in file without using pipe

command linegreppipesearch

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 of ksh), you could utilise process substitution

grep <pattern> <(tail -n5 yourfile.txt)

Where -n5 means get the five last lines.

Similarly,

grep <pattern> <(head -n5 yourfile.txt)

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.

diff -y <(brew leaves) <(brew list)

This gets rid of the pipe (|) character, but each substitution is in fact creating a pipe1.


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 to open a socket):

$ ksh93 -c 'readlink <(:)'
pipe:[620224]
$ ksh93 -c ': | readlink /proc/self/fd/0'
socket:[621301]

Related Question