將 grep 重定向到檔案不起作用

將 grep 重定向到檔案不起作用

我正在透過以下命令進行遞歸 grep:

grep -r "load" . > tmp.txt

但是,當我按 Enter 時,該命令不會執行,並且 bash 正在等待更多輸入。

我檢查了以下兩個答案,但它們無法解決我的問題。

為什麼 grep 不能與重定向一起使用?

如何將 tailf 和 grep 的輸出重新導向到文件

答案1

我也使用 Ubuntu 12.04,但出現此錯誤:

$ grep -r 'test' . > tmp.txt
grep: input file `./tmp.txt' is also the output

由於重定向會先展開,所以在執行tmp.txt之前會先在目前目錄下創建grep,導致出現錯誤。

如果我更改tmp.txt為其他路徑,例如/tmp/tmp.txt,則它可以正常工作。

我的grep版本:

$ grep --version
grep (GNU grep) 2.10
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.

相關內容