Use pipe of commands as argument for diff

后端 未结 5 1360
傲寒
傲寒 2021-01-30 06:39

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

5条回答
  •  独厮守ぢ
    2021-01-30 07:16

    The simplest approach is:

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

    The hyphen - as the filename is a specific notation that tells diff "use standard input"; it's documented in the diff man-page. (Most of the common utilities support the same notation.)

    The reason that backticks don't work is that they capture the output of a command and pass it as an argument. For example, this:

    cat `echo file`
    

    is equivalent to this:

    cat file
    

    and this:

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

    is equivalent to something like this:

    diff file "123
    234
    456"
    

    That is, it actually tries to pass 123234345 (plus newlines) as a filename, rather than as the contents of a file. Technically, you could achieve the latter by using Bash's "process substitution" feature that actually creates a sort of temporary file:

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

    but in your case it's not needed, because of diff's support for -.

提交回复
热议问题