bash 将两个文件重定向到标准输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4737794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:18:37  来源:igfitidea点击:

Redirecting two files to standard input

bashredirectsh

提问by Bobby Eickhoff

There are several unix commands that are designed to operate on two files. Commonly such commands allow the contents for one of the "files" to be read from standard input by using a single dash in place of the file name.

有几个 unix 命令旨在对两个文件进行操作。通常,此类命令允许通过使用单个破折号代替文件名从标准输入读取“文件”之一的内容。

I just came across a techniquethat seems to allow both files to be read from standard input:

我刚刚遇到了一种似乎允许从标准输入读取两个文件的技术

comm -12 <(sort file1) <(sort file2)

My initial disbelieving reaction was, "That shouldn't work. Standard input will just have the concatenation of both files. The command won't be able to tell the files apart or even realize that it has been given the contents of two files."

我最初的不相信反应是,“这不应该工作。标准输入将只是连接两个文件。该命令将无法区分文件,甚至无法意识到它已经给出了两个文件的内容。 ”

Of course, this construction does work. I've tested it with both command diffusing bash 3.2.51 on cygwin 1.7.7. I'm curious how and why it works:

当然,这种结构确实有效。我既进行了测试comm,并diff使用bash 51年3月2日在Cygwin 1.7.7。我很好奇它是如何以及为什么起作用的:

  • Why does this work?
  • Is this a Bash extension, or is this straight Bourne shell functionality?
  • This works on my system, but will this technique work on other platforms? (In other words, will scripts written using this technique be portable?)
  • 为什么这样做?
  • 这是 Bash 扩展,还是直接的 Bourne shell 功能?
  • 这适用于我的系统,但这项技术是否适用于其他平台?(换句话说,使用这种技术编写的脚本是否具有可移植性?)

采纳答案by Paused until further notice.

Bash, Korn shell (ksh93, anyway) and Z shell all support process substitution. These appear as files to the utility. Try this:

Bash、Korn shell(无论如何是 ksh93)和 Z shell 都支持进程替换。这些在实用程序中显示为文件。尝试这个:

$ bash -c 'echo <(echo)'
/dev/fd/63
$ ksh -c 'echo <(echo)'
/dev/fd/4
$ zsh -c 'echo <(echo)'
/proc/self/fd/12

You'll see file descriptors similar to the ones shown.

您将看到与所示类似的文件描述符。

回答by Tim Robinson

This is a standard Bash extension. <(sort file1)opens a pipe with the output of the sort file1command, gives the pipe a temporary file name, and passes that temporary file name on the commcommand line.

这是一个标准的 Bash 扩展。<(sort file1)sort file1命令的输出打开一个管道,给管道一个临时文件名,然后在comm命令行上传递这个临时文件名。

You can see how it works by getting echoto tell you what's being passed to the program:

您可以通过echo告诉您传递给程序的内容来了解它是如何工作的:

echo <(sort file1) <(sort file2)