Always try and break things down into there simplest steps, then try and put things together after. To start the first part, I’d construct myself a sample file.
$ echo -e "line 1 ABAnline 2 ABBnline 3 CCCn" > xxx $ cat xxx line 1 ABA line 2 ABB line 3 CCC
So now we have file
xxx. Now we need to use something that can act as program
yyy. Unix is full of commands that can fill in as stand ins for this, so let’s just pick
grep for now. Grep will find strings that we tell it we’re looking for so let’s tell it to find strings that contain “AB”.
$ cat xxx | grep AB line 1 ABA line 2 ABB
So we’ve just fulfilled the first 2 requirements.
cat xxxsends the contents of file
cat xxx | grep ABsends the contents to a program,
So the next bit, “pipe the output to the input of another program
zzz“, should be fairly straightforward too, since it’s more of the same, of what we’ve been doing with a command like
grep. So let’s use another
grep like so:
$ cat xxx | grep AB | grep BB line 2 ABB
Great, we’re almost there. We’ve just completed the 3rd requirement.
cat xxx | grep AB | grep BBtake the output from
grep ABas input, and generates its own output.
So the last bit, we just need to append the output from
grep BB. That’s easy. If you notice how we constructed the initial file,
xxx, we used a file redirection
> which will take the output from a command and dump it into a file. The redirector,
> will overwrite a file with content, even if it already exists. But we need to append. Luckily we can make use of another redirector,
>>. This will append the output from a command to a file that already exists.
Speaking of already existing, we need to construct file
xyz. So let’s use our
echo method we used to make
$ echo -e "previous line 1nprevious line 2" > xyz $ cat xyz previous line 1 previous line 2
Now let’s append the output from our command we’ve been constructing:
$ cat xxx | grep AB | grep BB >> xyz
We can check our results:
$ cat xyz previous line 1 previous line 2 line 2 ABB
And we’re done.