Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pipe of commands as argument for diff

Tags:

grep

bash

diff

I am having trouble with this simple task:

cat file | grep -E ^[0-9]+$ > file_grep diff file file_grep 

Problem is, I want to do this without file_grep

I have tried:

diff file `cat file | grep -E ^[0-9]+$` 

and

diff file "`cat file | grep -E ^[0-9]+$`" 

and a few other combinations :-) but I can't get it to work. I always get an error, when the diff gets extra argument which is content of file filtered by grep.

Something similar always worked for me, when I wanted to echo command outputs from within a script like this (using backtick escapes):

echo `ls` 

Thanks

like image 858
rluks Avatar asked Mar 23 '12 22:03

rluks


People also ask

How do you pipe the output of a command to another command?

You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

How do you pass the output of a command as an argument?

In this case, the output of the process and command substitution provided by parallel is being used as arguments to the cp command. We use the tokens “::::” and “:::” since parallel uses what is on the right as a file-argument and argument respectively.

What is pipe used for in CMD?

One of the most powerful shell operators is the pipe ( | ). The pipe takes output from one command and uses it as input for another.

Why we use diff command in Linux?

The Linux diff command is used to compare two files line by line and display the difference between them. This command-line utility lists changes you need to apply to make the files identical.


1 Answers

If you're using bash:

diff file <(grep -E '^[0-9]+$' file) 

The <(COMMAND) sequence expands to the name of a pseudo-file (such as /dev/fd/63) from which you can read the output of the command.

But for this particular case, ruakh's solution is simpler. It takes advantage of the fact that - as an argument to diff causes it to read its standard input. The <(COMMAND) syntax becomes more useful when both arguments to diff are command output, such as:

diff <(this_command) <(that_command) 
like image 111
Keith Thompson Avatar answered Oct 11 '22 13:10

Keith Thompson