Wednesday, March 9, 2016

Using the output of one command as the input for another command | pipe "|"


Using the output of one command as the input for another command | pipe "|"
In my previous two posts I described two commands which I use a lot. Grep to search for data and cut to display characters and/or columns from files.
As the title of this post suggests you can use the output of one command as the input of another.

In the following examples I will use the same fruit.txt example file which was used in my previous post about the cut command.
apple green tree
banana yellow tree
strawberry red plant

To send output data to another command you would need to use the pipe "|" character in between them. For example if you want to select only the first column of the fruit.txt file an the only the lines containing the word "tree" you would use the following command
grep "tree" fruit.txt | cut -d' ' -f1
apple
banana

Or the other way around
cut -d' ' -f1 fruit.txt | grep -v "strawberry"
apple
banana

But with the last command you would need to know which word to exclude using -v operator for the grep command. If you want to know how many lines are returned you can use the wc -l command to count the number of lines. Like this
cut -d' ' -f1 fruit.txt | grep -v "strawberry" | wc -l
2

No comments:

Post a Comment

How to create a software RAID array in Linux | mdadm

In my previous post I explained on the most common used RAID levels and their write penalties. In this post I will show how you c...