使用命令管作为参数的差异 [英] Use pipe of commands as argument for diff

查看:96
本文介绍了使用命令管作为参数的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的任务麻烦:

I am having trouble with this simple task:

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

问题是,我想这样做没有 file_grep

我曾尝试:

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

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

和其他几个组合:-)但我不能得到它的工作。
我总是得到一个错误,当差异获得额外的参数,它是由的grep 过滤的文件的内容。

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`

感谢

推荐答案

最简单的方法是:

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`

等同于这样的:

cat file

和这样的:

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

等同于这样的:

diff file "123
234
456"

也就是说,它实际上是试图通过 123234345 (加换行符)作为的文件名的,而不是作为的内容的文件。从技术上讲,你可以通过使用bash的进程​​替换功能,实际上是创建了一种临时文件的实现后者:

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]+$')

但在你的情况下,它不是必要的,因为差异的支持 -

这篇关于使用命令管作为参数的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆