將循環的 grep 命令重定向到單獨的文件

將循環的 grep 命令重定向到單獨的文件

我想使用 grep 使用檔案中列出的模式遞歸搜尋目錄,然後將每個結果儲存在自己的檔案中以供稍後參考。

我嘗試過(使用這個問題作為指導)並提出:

#!/bin/bash

mkdir -p grep_results   # For storing results

echo "Performing grep searches.."
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Seaching for $line.."
    grep -r "$line" --exclude-dir=grep_results . > ./grep_results/"$line"_infile.txt
done

echo "Done."

但是,當我運行它時,控制台會掛起,直到我按下 CTRL-C:

$ bash grep_search.sh search_terms.txt
Performing grep searches..

這個腳本的問題出在哪裡呢?還是我的做法是錯的?

答案1

這裡有幾個問題:

  1. 循環while不讀取任何輸入。正確的格式是

    while read line; do ... ; done < input file
    

    或者

    some other command | while read ...
    

    因此,您的循環掛起,等待輸入。您可以透過執行腳本然後輸入任何內容並按 Enter 鍵來測試這一點(在這裡,我輸入了foo):

    $ foo.sh 
    Performing grep searches..
    foo
    Searching for foo..
    

    您可以透過在您的 中添加提示來改進這一點read

    while IFS='' read -p "Enter a search pattern: " -r line ...
    

    不過,它仍然會運行,直到你用Ctrl+停止它C

  2. (這|| [[ -n "$line" ]]意味著「或變數 $line 不為空」)永遠不會被執行。由於read掛起,“OR”永遠不會到達。無論如何,我不明白你想要它做什麼。如果您想要搜尋$line是否$line已定義並使用read如果未定義,則需要類似以下內容:

    if [[ -n "$line" ]]; then
         grep -r "$line" --exclude-dir=grep_results > ./grep_results/"$line"_infile.txt
    else
        while IFS='' read -p "Enter a search pattern: " -r line || [[ -n "$line" ]]; do
          grep -r "$line" --exclude-dir=grep_results > ./grep_results/"$line"_infile.txt
        done
    fi
    

    這裡,如果$line沒有定義,仍然需要手動輸入。更簡潔的方法是將文件提供給循環while

    while IFS='' read -r line || [[ -n "$line" ]]; do
      grep -r "$line" --exclude-dir=grep_results > ./grep_results/"$line"_infile.txt
    done < list_of_patterns.txt
    

相關內容