为什么我不能重定向到 grep 用于输入的文件?

Why can't I redirect to the file that grep uses for input?

File1:
foo
bar
baz

File2:
bar.patch

grep -f file1 file2 > file1

预期结果,file1 包含 bar.patch,但它是空的。

grep 如何处理输入文件以致我无法重定向到它?

重定向 > 发生在命令执行之前,因此 grep 看到空文件而 returns 什么也没有。如果你真的想写入同一个文件,你可以使用 sponge 命令(它是 moreutils 的一部分)。它缓冲输入并仅在数据结束后写入输出文件。示例:

grep -f file1 file2 | sponge file1

检查 bash manual 以了解有关重定向的详细信息:

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection allows commands’ file handles to be duplicated, opened, closed, made to refer to different files, and can change the files the command reads from and writes to. Redirection may also be used to modify file handles in the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.

或者只是重定向到一个临时文件,然后 mv 它通过 file1

grep -f file1 file2 > file3
mv -f file3 file1