Concatenating Commands with Pipes and Substitution

From docwiki
Revision as of 16:35, 21 March 2020 by Mond (talk | contribs)
Jump to: navigation, search

Motivation

In the last Example we have seen how we can redirect the input and output of commands from and to files. Now often enough we only produce output of one command for the purpose of feeding it to another program and we are not interested in the intermediate outputs.

In other instances we have the output of one program that we want to substitute on the command line as arguments to an other program.

With these tools we are extremely flexible and can create powerful commands.

Pipes

If we want the output of one program as the input of another we can put a | vertial bar (in this context called pipe symbol) in between them:

$ ls -l | wc -l 

So the above example would run the ls -l command that lists the files and directories in our current directory and then count the lines. So we know how many of those are there.

$ find . | grep -i doc | grep -v cache 

The find . would list all files and directories in all sub-directories form the current directory on (the dot denotes the current directory). Then the output is passed to the grep command. Grep filters out only lines that correspond to that string (actually it can do regular-expression) and only lets those through. The -i says that it should match case-insensitive. Finally the output is passed to another grep command: This time with the option -v wich inverts the match: That filters out all matching lines. In our case any file or directory name that has the word cache in it.

One specially useful tool for using with pipe is less. less is the successor of more. If the output of a command is very long and would scroll over several pages you want to page through it one page at a time.

$ find /usr/bin/