Cod*_*lue 3 shell io-redirection files arguments
假设我做了一个grep给我很多结果的。我想使用 grep 的输出并将其传递给一个将文件名作为第一个参数的命令。例如 -
myCommand filename.txt
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情 -
grep "xyz" | myCommand
Run Code Online (Sandbox Code Playgroud)
However, since myCommand doesn't read from stdin, this piping does not work. I don't want to create a temporary file on disk with the results of grep. Is it possible by any other means to create a "file", say in memory and let myCommand use that?
A simple solution is to use Bash's support for process substitution, like this:
myCommand <(grep "xyz" somefile)
Run Code Online (Sandbox Code Playgroud)
This will connect the output of the grep command to a file descriptor and then pass /dev/fd/NNN (where NNN is the fd number) to your command as the input file (for example, your command might actually get run as myCommand /dev/fd/63). This solution does not create a temporary file.
You can also create a named pipe and use that to transfer data around:
$ mkfifo /tmp/myfifo
$ grep "xyz somefile > /tmp/myfifo &
$ myCommand /tmp/myfifo
Run Code Online (Sandbox Code Playgroud)
But really, the first solution is simpler.
Stephane Chazelas comments:
zsh 还有 myCommand =(grep xyz somefile) 它使用一个普通的临时文件(在 myCommand 不能接受管道的情况下)。
这很重要,因为某些命令希望能够对其输入文件执行随机访问,这不适用于管道。使用此语法,您可以获得临时文件的好处,而无需担心自己清理它们。